Philip (bluesmoon) wrote,
Philip
bluesmoon

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.


Posting this through lynx
Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 6 comments