unsigned char 数组与 long 类型互转
C/C++ 中,如果需要将 int 或者 unsigned int 以及 long 和 unsigned long 类型数据互转,则可以参考一下代码
#include<cstdio> typedef unsigned int uint32_t; typedef unsigned long int uint64_t; typedef unsigned char uint8_t; bool transferLong2ByteArray(uint8_t* byte, uint8_t length, uint64_t version){ uint64_t temp = version; for(uint8_t i = 0; i < length; ++i){ uint8_t res = (uint8_t)(temp & 0xff); byte[i] = res; temp = temp >> 8; } return true; } uint64_t transferByteArrayToLong(uint8_t* byte, uint8_t length) { uint64_t version = 0; #if 1 for(int i = 0; i < length; ++i){ uint64_t temp = byte[i]; version |= (temp << i * 8); } #else long s = 0; long s0 = (byte[0] & 0xff); long s1 = (byte[1] & 0xff) << 8; long s2 = (byte[2] & 0xff) << 16; long s3 = (byte[3] & 0xff << 24); version = s0 | s1 | s2 | s3; #endif return version; } int main() { uint32_t version = 0x000710; uint64_t longVersion = (uint64_t)version; uint8_t byte[4] = {0}; transferLong2ByteArray(byte, 4, longVersion); uint64_t finalVersion = transferByteArrayToLong(byte, 4); printf("vrsion %ld\n", finalVersion); return 0; }