1

I a writing a routine to append bytes to a byte_array like so

unsigned long speed = 0xfeb;
char byteArray[8];
bzero(byteArray,8); //fills every of the 8 bytes with zero
memcpy(byteArray,&speed ,4); //copies 4 bytes from speed to byteArray

After the operation i am expecting byteArray to have the value 0xfeb but it turns out that byteArray has the value 0xebf

What is happening ? is it normal for memcpy to force the result to little-endianness ? What should i do to get the result without the change of endianness ?

salimsaid
  • 3,186
  • 4
  • 15
  • 20

2 Answers2

11

memcpy just copies bytes and doesn't care about endianness:

Copies count bytes from the object pointed to by src to the object pointed to by dest. Both objects are reinterpreted as arrays of unsigned char.

If you're on a little-endian machine it will copy LSB first. On a big-endian machine it will copy MSB first, and you will get the expected 0x0f 0xeb.


Unrelated, but you shouldn't use hard-coded values, but rather sizeof, e.g.

unsigned long speed = 0xfeb;
char byteArray[sizeof(speed)];
bzero(byteArray, sizeof(byteArray));
memcpy(byteArray, &speed , sizeof(speed));
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
2

memcpy does exactly what it says on the tin: it copies memory. It does not mess about with the ordering of bytes.

Endianness is only relevant if you want to know how a particular bit pattern maps to the value of the integral type. Folk tend to blame endianness for all sorts of things: in the majority of occasions it has a benign effect, and that's the case here.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483