数据类型转换 [英] Data type conversion
问题描述
Hi.guys!
我想将unsigned long转换为unsigned char [],或将unsigned char []转换为unsigned long。但我不会。
please帮我!谢谢
示例:
unsigned long a = 8; // memery中的数据是08 00 00 00< - 如何转换?
字节a [5]; //如何将其转换为Ulong变量
a [0] = 0x08;
a [1] = 0x00;
a [2] = 0x00;
a [3] = 0x00;
a [4] = 0x00;
Hi.guys!
I want to convert unsigned long to unsigned char[], or unsigned char[] into unsigned long.But I will not.
please help me! Thanks
Example:
unsigned long a = 8; // The data in memery is 08 00 00 00 <- how to convert ?
byte a[5]; // how to convert it into a Ulong variable
a[0] = 0x08;
a[1] = 0x00;
a[2] = 0x00;
a[3] = 0x00;
a[4] = 0x00;
推荐答案
unsigned char *tc;
unsigned long tl = 8;
tc = (unsigned char *)(&tl);
unsigned char al[sizeof(unsigned long)];
// Copy bytes to array
memcpy(&al, tc, sizeof(unsigned long));
// Back to ulong
unsigned long *tlptr = (unsigned long *) al;
for(int i = 0; i < sizeof(unsigned long); i++)
std::cout << std::hex << (int) tc[i] << std::endl;
std::cout << std::hex << *tlptr << std::endl;
或者,您可以使用union
:
Alternatively, you could use aunion
:
#include <iostream>
using namespace std;
union ULB
{
unsigned long ul;
unsigned char b[4];
};
int main()
{
ULB ulb;
ulb.ul = 8;
for (const auto & b : ulb.b)
cout << hex << (int)b << " ";
cout << endl;
ulb.b[0] = 0x32;
cout << hex << ulb.ul << endl;
}
这篇关于数据类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!