2

What would the equivalent of this Perl line be in C?

unpack('J>', pack('B*', $s))

Depending on the build of Perl, it takes the binary representation of 4 or 8 bytes

"11110000000000000000000001010001"

or

"0000000000000000000000000000000011110000000000000000000001010001"

and returns the 32-bit or 64-bit integer that represented by those bytes in big-endian order.

0xF0000051
ikegami
  • 367,544
  • 15
  • 269
  • 518

1 Answers1

1

To parse the binary string you can use strtol() and to make it big endian you can use htonl():

int32_t value = strtol("1010001", NULL, 2);
int32_t big_endian = htonl(value);

htonl() strictly speaking is not part of C, but it's common for networking code and it puts a long (4 bytes) into network order (which happens to be big endian). Alternatively, you have to test if you're already on a big endian box and then you can do the bitwise ops yourself.

FatalError
  • 52,695
  • 14
  • 99
  • 116
  • The names are backwards. Should really be: `int32_t big_endian = strtol("1010001", NULL, 2); int32_t big_value = htonl(big_endian);` – ikegami Feb 22 '13 at 00:11
  • this answer is not complete, since 32-bit and 64-bit values should be handled, according to the question. – SirDarius Feb 22 '13 at 00:17
  • If 64 bit values, then you can use strtoll() to parse the string. There is, unfortunately, no ntonll() call so there you will probably have to roll your own. – Sean Conner Feb 22 '13 at 00:49
  • I was mostly trying to understand the solution presented @ http://stackoverflow.com/questions/12520462/perl-quick-switch-from-quaternary-to-decimal as both versions don't match... – Alexander Koch Feb 22 '13 at 01:14