0

## Arudino 16進位轉10進位

id[3], id[2], id[1], id[0]

389A8881的10進位949651585呢

ant1017 iT邦新手 3 級 ‧ 2020-09-18 14:22:06 檢舉
hex to dec in C

### 2 個回答

2

• `(unsigned int*)a`:
將陣列 a 的地址轉為 int 的指標
• `*(unsigned int*)a`:
將指標的值取出，由於是 int 型態，所以會抓取 4個 byte 的資料
``````#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;
}
``````

``````#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;
}
``````

``````#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;
}
``````

1

iT邦研究生 2 級 ‧ 2020-09-18 13:58:18

``````#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
``````