[philiptellis] /bb|[^b]{2}/
Never stop Grokking


Friday, January 02, 2004

Endians

How would one transfer an int to a byte array?

This is code that I've seen:

memcpy(&byte_array[start], &value, sizeof(value));

It, however, doesn't consider the architecture's byteorder, and will not work correctly on the "other" sex.

This is my version:
for(x = 0; x < sizeof(value); x++, value>>=8)
        byte_array[start+x] = value & 0xff;
It works because it deals only with values, and cares nothing about byte order. Yes, I am looking at the value as a sequence of bits, but I do not care how many bits there are, and regardless of byteorder, the bits are always arranged with msb to the left and lsb to the right.

0 comments :

Post a Comment

...===...