C-unsigned int到unsigned char数组的转换 [英] C - unsigned int to unsigned char array conversion
问题描述
我有一个无符号的整数(2个字节),我想将其转换为无符号的char类型.通过搜索,我发现大多数人建议执行以下操作:
I have an unsigned int number (2 byte) and I want to convert it to unsigned char type. From my search, I find that most people recommend to do the following:
unsigned int x;
...
unsigned char ch = (unsigned char)x;
正确的方法吗?我问是因为无符号char是1个字节,我们将2个字节的数据强制转换为1个字节.
Is the right approach? I ask because unsigned char is 1 byte and we casted from 2 byte data to 1 byte.
为防止任何数据丢失,我想创建一个无符号char []数组并将单个字节保存到该数组中.我被困在以下几点:
To prevent any data loss, I want to create an array of unsigned char[] and save the individual bytes into the array. I am stuck at the following:
unsigned char ch[2];
unsigned int num = 272;
for(i=0; i<2; i++){
// how should the individual bytes from num be saved in ch[0] and ch[1] ??
}
此外,我们如何将未签名的char [2]转换回unsigned int .
非常感谢.
推荐答案
在这种情况下,您可以使用memcpy
:
You can use memcpy
in that case:
memcpy(ch, (char*)&num, 2); /* although sizeof(int) would be better */
此外,如何将未签名的char [2]转换回unsigned int.
Also, how would be convert the unsigned char[2] back to unsigned int.
以同样的方式,只需反转memcpy的参数即可.
The same way, just reverse the arguments of memcpy.
这篇关于C-unsigned int到unsigned char数组的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!