C++ equivalent of 'pack' in Perl

后端 未结 2 2026
面向向阳花
面向向阳花 2020-12-21 18:46

How do I write C++ code that does what the pack -N option does in Perl?

I want to convert an integer variable to some binary form such that the unpack -

2条回答
  •  我在风中等你
    2020-12-21 19:14

    It takes 4 bytes and forms a 32-bit int as follows:

    uint32_t n;
    n = buf[0] << 24
      | buf[1] << 16
      | buf[2] <<  8
      | buf[3] <<  0;
    

    For example,

    uint32_t n;
    unsigned char buf[4];
    size_t bytes_read = fread(buf, 1, 4, stream);
    if (bytes_read < 4) {
       if (ferror(stream)) {
          // Error
          // ...
       }
       else if (feof(stream)) {
          // Premature EOF
          // ...
       }
    }
    else {
       n = buf[0] << 24
         | buf[1] << 16
         | buf[2] <<  8
         | buf[3] <<  0;
    }
    

提交回复
热议问题