I found this code on SO.
unsigned char * SerializeInt(unsigned char *buffer, int value)
{
/* Write big-endian int value into buffer; assumes 32-bit int and 8-bit char. */
buffer[0] = value >> 24;
buffer[1] = value >> 16;
buffer[2] = value >> 8;
buffer[3] = value;
return buffer + 4;
}
You can see the code claims it is writing an integer into the buffer, in a Big Endian Way.
My question is: Does this function work correctly on both Little endian and Big endian machines? In other words, on both LE and BE machines, does it store the number to buffer in a Big Endian Way? And if yes, Why?
Big-Endian is defined as with the big end (i.e. most significant bit/byte) first. So, yes, the function writes the
value
in big-endian format to thebuffer
.However, returning a pointer one past the buffer strikes me as unusual.
The code will always write the
integer
inchar
array in big-endian way. This is because you are always saving MSB atbuffer[0]
and LSB atbuffer[3]
.Suppose in a little endian machine:
you have number
0x11223344
: (in hexadecimal format)The same representation on a big endian machine will be:
In both machines,
integer << 24
will mean MSB and(int8_t)integer
will mean LSB.Whatever is the endianness of your system, your
SerializeInt
function will storevalue
in big endian in the arraybuffer
. It is stored as big endian as it writes the most significant byte first. Remember that when you evaluatevalue
it has no endianness per se, it's like any mathematical value.Apart from the already posted answers regarding endianess...
No, because you use bit-wise arithmetic on the default
int
type. If theint
is negative, the behavior is implementation-defined. In general, it doesn't make any sense whatsoever to use bit-wise operators on signed integers.Furthermore, your code relies on
int
being 32 bits, of which there are no guarantees.So your code is completely non-portable. Fix it in the following way: