1

I need to read in unsigned char * bytes which are in reverse order to the native order. At the moment I have lots of little routines along the following lines:

uint8_t * bytes;
uint32_t r;
bytes = pt;
r = (((((bytes[0] << 8) + bytes[1]) << 8) + bytes[2]) << 8) + bytes[3];
pt += 4;
return r;

Is there a standard or portable way to do this kind of job, or do I have to hack up functions like this?

  • @WhozCraig - I remember your name from somewhere, you seem to like jumping on people. It's nothing to do with network order, where does it say network order? The bytes are from a TrueType font file. –  Jun 16 '14 at 01:13

1 Answers1

1

The socket library for your platform provides the following functions which do these conversions:

  • ntohs - Network to Host Short (16-bit)
  • htons - Host to Network Short (16-bit)
  • ntohl - Network to Host Long (32-bit)
  • htonl - Host to Network Long (32-bit)

To implement your code above, you can:

r = ntohl(*(uint32_t *)bytes);
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • Those functions look like they may be useful, but the actual reversal is within a TrueType font rather than being "network order". I'm not exactly sure whether I should use "network byte order" as a substitute for "TrueType font byte order". I'll just check this and see if this fits the problem. –  Jun 16 '14 at 01:09
  • @ChewyDragees: "Network byte order" is defined as big-endian (most significant byte first). You'll probably find that the TrueType byte order is the same as network byte order. – Greg Hewgill Jun 16 '14 at 01:10
  • I did find that. Thanks Greg, this is the right answer. –  Jun 16 '14 at 01:11
  • Doesn't do uint64_t though. I guess I can just to that my self. –  Jun 16 '14 at 01:22
  • 1
    @ChewyDragees for 64-bit endian conversion you can use [ntohll](http://msdn.microsoft.com/en-us/library/windows/desktop/jj710202%28v=vs.85%29.aspx) on Windows and some [Unix](http://www.unix.com/man-page/opensolaris/3socket/ntohll/) implementations. For some others you need to use [htole64](http://www.manualpages.de/OpenBSD/OpenBSD-5.0/man3/htole64.3.html) or [betoh64](http://stackoverflow.com/a/809919/995714) – phuclv Jun 16 '14 at 02:02