C++ equivalent of 'pack' in Perl

妖精的绣舞 提交于 2019-11-28 11:19:34

问题


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 -N option on it gives back the integer variable.

My integer variable name is timestamp.

I found that it is related to htonl, but still htonl(timestamp) does not give the binary form.


回答1:


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/




回答2:


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;
}


来源:https://stackoverflow.com/questions/24863649/c-equivalent-of-pack-in-perl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!