Navel Gazing: Integer to Byte Conversions

on C, C++, Navel Gazing

I’ve got a thing, and it reads a series of bytes over a named pipe because.

It just so happens that I know that the first four bytes sent over the pipe is an integer (because of a previously agreed upon protocol), and it just so happens that I really need that to be an integer, and not a unsigned char[4] (which is what I have).

So I wrote the following code, because I am Smart and Attractive:

int i = (i << 8) + arr[0];
i = (i << 8) + arr[1];
i = (i << 8) + arr[2];
i = (i << 8) + arr[3];

And immediately realized that I had managed to convert my four bytes into an integer by interpreting the bytes as being encoded in big-endian, where it was actually four bytes encoded in little-endian (the other side of the named pipe is running on the same machine).

Okay, so that’s an easy fix:

int i = (i << 8) + arr[3];
i = (i << 8) + arr[2];
i = (i << 8) + arr[1];
i = (i << 8) + arr[0];

Success, I am incredible.

BUT WAIT! What if some hypothetical future revision of my thing runs on a processor that is BIG ENDIAN – in this case, I might actually screw up the endianness the other direction!

NOTE: This is where the navel gazing comes in.

Okay! So. What’s the best way to portably define a byte-array -> integer conversion function. The first thing that came to mind was to mutter an expletive and define a union:

union byteint {
    unsigned char bytes[4];
    int integer;
} b;

b.bytes = arr;

But then I thought that they are all going to make fun of me for doing it that way, that there is a better way and if only I could know this way, my life would be much improved.

Can you think of a Better Way™?

Update - Yes, Virginia, I'm Dumb

I tossed this out to a few coworkers of mine, Cody and Zac. It took them but a moment to point that reinterpret_cast<>() could be used and should be completely portable, avoiding the need for a union.

In my defense, I had considered reinterpret_cast but immediately felt shame for thinking of it and its conjurers ways. Unconscious bias, I guess.

comments powered by Disqus