在採用小端序 (Little-Endian) 的機器上,降冪的陣列順序剛好和 int 資料存放的順序相同,可以直接用 int 的指標去取。
(unsigned int*)a
:*(unsigned int*)a
:#include <stdio.h>
int main()
{
unsigned char a[4];
a[0] = 0x81;
a[1] = 0x88;
a[2] = 0x9A;
a[3] = 0x38;
printf("%u", *(unsigned int*)a);
return 0;
}
如果機器採用的 Endian 不確定的話,需要另外處理。
#include <stdio.h>
unsigned int toDec(unsigned char a[])
{
//檢查機器是否採用小端序
const unsigned short flag = 1;
const unsigned char is_little_endian =
*((unsigned char*)&flag) == 1;
if (is_little_endian)
//小端序的話直接回傳
return *(unsigned int*)a;
else
{
//不是小端序則進行反轉
unsigned char b[4];
for(int i=0; i<4; i++)
b[i] = a[4-i-1];
return *(unsigned int*)b;
}
}
int main()
{
unsigned char a[4];
a[0] = 0x81;
a[1] = 0x88;
a[2] = 0x9A;
a[3] = 0x38;
printf("%u", toDec(a));
return 0;
}
發現可以直接用位移達到同樣的效果,而且不會有 Endian 的問題。
#include <stdio.h>
int main()
{
unsigned char a[4];
a[0] = 0x81;
a[1] = 0x88;
a[2] = 0x9A;
a[3] = 0x38;
unsigned int b = a[0] +
(a[1] << 8 ) +
(a[2] << 16) +
(a[3] << 24) ;
printf("%x", b); //389a8881
return 0;
}
我是在VS C++內寫的,但概念都一樣,自行轉換即可
程式碼
#include <iostream>
int main()
{
uint8_t id[4];
id[3] = 0x38;
id[2] = 0x9A;
id[1] = 0x88;
id[0] = 0x81;
printf("%d", *(uint32_t*)id);
}
輸出
949651585