int char[] memcpy()和Big-Endian Little-Endian(大小端)的事

a variable

1
uint32 var0 = 0x12345678;

Big-Endian memory layout:

1
2
3
4
00000000  0x12
00000001 0x34
00000002 0x56
00000003 0x78

Little-Endian:

1
2
3
4
00000000  0x78
00000001 0x56
00000002 0x34
00000003 0x12

a char[]

1
char var1[4] = {0x12,0x34,0x56,0x78};

memory layout:

1
2
3
4
00000000  0x12
00000001 0x34
00000002 0x56
00000003 0x78

if i use memcpy to copy var1 to a integer var3:

1
2
uint32 var2 = 0;
memcpy(&var2, var1, sizeof(var1));

then you will find that the var2 not equal the var0, this is beacuse in windows/linux(mostly) use Little-Endian as the default, So you need to exchange var1 to 0x78,0x56,0x34,0x12, or rewrite a memcpy_ function.

1
2
3
4
5
6
7
8
9
10
11
12
void* memcpy_(void* _Dst, const void* _Src, size_t _Size) {
uint8_t* d = (uint8_t*)_Dst;
uint8_t* s = (uint8_t*)_Src;
if (_Dst == _Src) {
return _Dst;
}
int i = 0;
while (_Size-- > 0) {
d[i]=s[_Size];
i++;
}
}

this problem is easy, but a bit confusing, especially when dealing with a binary file.

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×