C語言實現多字節(jié)與整型數據的相互轉換
數據類型定義
typedef signed char int8_t;
typedef signed short int int16_t;
typedef signed int int32_t;
typedef signed __INT64 int64_t;
1
2
3
4
1、將多字節(jié)(2、4、8字節(jié))轉換為整型數據(16、32、64位)
(舉例:2字節(jié) {0x12, 0x34} → 16位整型 0x1234)
(舉例:4字節(jié) {0x12, 0x34, 0x56, 0x78} → 32位整型 0x12345678)
(舉例:8字節(jié) {0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56} → 64位整型 0x1234567890123456)
/***************************
函數名: ArrayToVariable
功能描述: 將多字節(jié)(2、4、8字節(jié))轉換為整型數據(16、32、64位)
參數: Array: 待轉換數組
Length: 待轉換數組的長度
返回: 轉換后的整型數據
***************************/
uint64_t ArrayToVariable(uint8_t *Array, uint8_t Length)
{
uint64_t Variable = 0;
if(Length == 2)
{
Variable = (((uint16_t)Array[0] << 8) + ((uint16_t)Array[1]));
}
else if(Length == 4)
{
Variable = (((uint32_t)Array[0] << 24) + ((uint32_t)Array[1] << 16)
+ ((uint32_t)Array[2] << 8) + ((uint32_t)Array[3]));
}
else if(Length == 8)
{
Variable = (((uint64_t)Array[0] << 56) + ((uint64_t)Array[1] << 48)
+ ((uint64_t)Array[2] << 40) + ((uint64_t)Array[3] << 32)
+ ((uint64_t)Array[4] << 24) + ((uint64_t)Array[5] << 16)
+ ((uint64_t)Array[6] << 8) + ((uint64_t)Array[7]));
}
return Variable;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2、將16位整型數據轉換為2字節(jié)
(舉例: 16位整型數據 0x1234 → 2字節(jié)數組 {0x12,0x34})
/***************************
函數名: Variable16ToArray
功能描述: 將16位整型數據轉換為2字節(jié)
參數: Variable:待轉換的16位整型數據
Array:轉換后的2字節(jié)數組
***************************/
void Variable16ToArray(uint8_t *Array, uint32_t Variable)
{
*(Array) = (uint8_t)(Variable >> 8);
*(Array + 1) = (uint8_t)(Variable);
}
1
2
3
4
5
6
7
8
9
10
11
12
3、將32位整型數據轉換為4字節(jié)
(舉例: 32位整型數據 0x12345678 → 4字節(jié)數組 {0x12,0x34,0x56,0x78})
/***************************
函數名: Variable32ToArray
功能描述: 將32位整型數據轉換為4字節(jié)
參數: Variable:待轉換的32位整型數據
Array:轉換后的4字節(jié)數組
***************************/
void Variable32ToArray(uint8_t *Array, uint32_t Variable)
{
*(Array) = (uint8_t)(Variable >> 24);
*(Array + 1) = (uint8_t)(Variable >> 16);
*(Array + 2) = (uint8_t)(Variable >> 8);
*(Array + 3) = (uint8_t)(Variable);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
4、將64位整型數據轉換為8字節(jié)
(舉例: 64位整型數據 0x1234567890123456 → 4字節(jié)數組 {0x12,0x34,0x56,0x78,0x90,0x12,0x34,0x56})
/***************************
函數名: Variable64ToArray
功能描述: 將64位整型數據轉換為8字節(jié)
參數: Variable:待轉換的64位整型數據
Array:轉換后的8字節(jié)數組
***************************/
void Variable64ToArray(uint8_t *Array, uint64_t Variable)
{
*(Array) = (uint8_t)(Variable >> 56);
*(Array + 1) = (uint8_t)(Variable >> 48);
*(Array + 2) = (uint8_t)(Variable >> 40);
*(Array + 3) = (uint8_t)(Variable >> 32);
*(Array + 4) = (uint8_t)(Variable >> 24);
*(Array + 5) = (uint8_t)(Variable >> 16);
*(Array + 6) = (uint8_t)(Variable >> 8);
*(Array + 7) = (uint8_t)(Variable);
}
————————————————
原文鏈接:https://blog.csdn.net/lnfiniteloop/article/details/120015554
*博客內容為網友個人發(fā)布,僅代表博主個人觀點,如有侵權請聯(lián)系工作人員刪除。