如何正确地将unsigned char数组转换为uint32_t [英] How to properly convert an unsigned char array into an uint32_t
问题描述
所以,我试图将 unsigned char
的数组转换为 uint32_t
,但继续获取每次不同的结果:
unsigned char buffer [] = {0x80,0x00,0x00,0x00} ;;
uint32_t num =(uint32_t *)& buffer;
现在,我一直收到此警告:
< blockquote>
警告:初始化从指针无整数转换
当我更改 num
到 * num
我没有得到那个警告,但这不是真正的问题( UPDATE:好吧,那些可能是相关的,现在我想到它。),因为每次我运行代码有不同的结果。其次, num
,一旦正确转换,应该是 128
,但如果我需要更改缓冲区的字节顺序
谢谢!
您尝试过这个吗?
num =(uint32_t)buffer [0] < 24 |
(uint32_t)buffer [1]< 16 |
(uint32_t)buffer [2]< 8 |
(uint32_t)buffer [3];
这样就可以控制字节序和其他。
<指向一个
char
指针并将其解释为更大的东西真的不安全。有些机器需要指向整数的指针对齐。 So, I'm trying to convert an array of unsigned char
s into an uint32_t
, but keep getting different results each time:
unsigned char buffer[] = {0x80, 0x00, 0x00, 0x00};;
uint32_t num = (uint32_t*)&buffer;
Now, I keep getting this warning:
warning: initialization makes integer from pointer without a cast
When I change num
to *num
i don't get that warning, but that's not actually the real problem (UPDATE: well, those might be related now that I think of it.), because every time I run the code there is different results. Secondly the num
, once it's cast properly, should be 128
, but If I need to change the endianness of the buffer I could manage to do that myself, I think.
Thanks!
Did you try this ?
num = (uint32_t)buffer[0] << 24 |
(uint32_t)buffer[1] << 16 |
(uint32_t)buffer[2] << 8 |
(uint32_t)buffer[3];
This way you control endianness and whatnot.
It's really not safe to cast a char
pointer and interpret it as anything bigger. Some machines expect pointers to integers to be aligned.
这篇关于如何正确地将unsigned char数组转换为uint32_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!