Why does memcpy / memmove return data when copying an int to a byte buffer?

So my question is pretty simple:

I need to populate a char / unsigned char array with some information. Some middle values ​​are taken from short / int types, and this happens:

the code:

int foo = 15; //0x0000000F
unsigned char buffer[100]={0};

..
memcpy(&buffer[offset], &foo, sizeof(int)); //either memmove
...

Conclusion:

... 0F 00 00 00 ..

So, now I have written a function to change these fields, but I do not consider this an intelligent solution, as it affects the runtime, resources and development time.

Is there an easier way to do this?

: , - endian, . int/short big-endian, , , / endian, , .

. ++

+4
4

, endian. (- , uint8_t) .

Edit

, , , . , , .

- , . , , endianness. , - . . Se,

https://linux.die.net/man/3/htonl

, , .

void writeUInt32ToBufferBigEndian(uint32_t number, uint8_t* buffer)
{
    buffer[0] = (uint8_t) ((number >> 24) & 0xff);
    buffer[1] = (uint8_t) ((number >> 16) & 0xff);
    buffer[2] = (uint8_t) ((number >> 8) & 0xff);
    buffer[3] = (uint8_t) ((number >> 0) & 0xff);
}
+5

memcpy, memmove . , , , 32- 15 (0F ) .

, , . , , big-endian, 00 00 00 0F, , . . - , , big-endian - : .

Wikipedia .

, , big-endian, :

#include <stdint.h>

int foo = 15; //0x0000000F
unsigned char buffer[100] = { 0 };

..
buffer[offset + 0] = ((uint32_t)foo >> 24) & 0xFF;
buffer[offset + 1] = ((uint32_t)foo >> 16) & 0xFF;
buffer[offset + 2] = ((uint32_t)foo >>  8) & 0xFF;
buffer[offset + 3] = ((uint32_t)foo >>  0) & 0xFF;
...
+6

x86 . . 0x12345678 78, 56, 34, 12 .

+2

" " - "". ? 0F , , " " (.. ) . . ""?

, "" , , "" 0x0000000F , " - " : , .

, /. , , , ( C) . - , .

+1

Source: https://habr.com/ru/post/1672360/


All Articles