如何正确地将unsigned char数组转换为uint32_t [英] How to properly convert an unsigned char array into an uint32_t

查看:2287
本文介绍了如何正确地将unsigned char数组转换为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 chars 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆