C++ equivalent of 'pack' in Perl

后端 未结 2 2019
面向向阳花
面向向阳花 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;
    }
    
    0 讨论(0)
  • 2020-12-21 19:36

    I wrote a library, libpack, similar to Perl's pack function. It's a C library so it would be quite usable from C++ as well:

    FILE *f;
    fpack(f, "u32> u32>", value_a, value_b);
    

    A u32 > specifies an unsigned 32-bit integer in big-endian format; i.e. equivalent to Perl's N format to pack().

    http://www.leonerd.org.uk/code/libpack/

    0 讨论(0)
提交回复
热议问题