C语言实现多字节(2、4、8字节)与整型数据(16、32、64位)的相互转换
程序员文章站
2024-03-16 18:24:22
...
-
数据类型定义
typedef signed char int8_t; typedef signed short int int16_t; typedef signed int int32_t; typedef signed __INT64 int64_t;
-
1、将多字节(2、4、8字节)转换为整型数据(16、32、64位)
- (举例:2字节 {0x12, 0x34} → 16位整型 0x1234)
- (举例:4字节 {0x12, 0x34, 0x56, 0x78} → 32位整型 0x12345678)
-
(举例:8字节 {0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56} → 64位整型 0x1234567890123456)
/*************************** 函数名: ArrayToVariable 功能描述: 将多字节(2、4、8字节)转换为整型数据(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; }
-
2、将16位整型数据转换为2字节
-
(举例: 16位整型数据 0x1234 → 2字节数组 {0x12,0x34})
/*************************** 函数名: Variable16ToArray 功能描述: 将16位整型数据转换为2字节 参数: Variable:待转换的16位整型数据 Array:转换后的2字节数组 ***************************/ void Variable16ToArray(uint8_t *Array, uint32_t Variable) { *(Array) = (uint8_t)(Variable >> 8); *(Array + 1) = (uint8_t)(Variable); }
-
(举例: 16位整型数据 0x1234 → 2字节数组 {0x12,0x34})
-
3、将32位整型数据转换为4字节
-
(举例: 32位整型数据 0x12345678 → 4字节数组 {0x12,0x34,0x56,0x78})
/*************************** 函数名: Variable32ToArray 功能描述: 将32位整型数据转换为4字节 参数: Variable:待转换的32位整型数据 Array:转换后的4字节数组 ***************************/ 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); }
-
(举例: 32位整型数据 0x12345678 → 4字节数组 {0x12,0x34,0x56,0x78})
-
4、将64位整型数据转换为8字节
-
(举例: 64位整型数据 0x1234567890123456 → 4字节数组 {0x12,0x34,0x56,0x78,0x90,0x12,0x34,0x56})
/*************************** 函数名: Variable64ToArray 功能描述: 将64位整型数据转换为8字节 参数: Variable:待转换的64位整型数据 Array:转换后的8字节数组 ***************************/ 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); }
-
(举例: 64位整型数据 0x1234567890123456 → 4字节数组 {0x12,0x34,0x56,0x78,0x90,0x12,0x34,0x56})
上一篇: Mm