转换的字节数组整数 [英] Converting bytes array to integer

查看:132
本文介绍了转换的字节数组整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有型的4字节数组(数据) uint8_t有,从而重新presents一个高速数据整数。我试图施放此阵 uint32_t的整数(速度),乘以10这个速度,然后将其恢复到4字节数组(数据)。数据格式如下code清楚。
我总是得到错误:


  

分配与数组类型前pression


在code:

 挥发性uint8_t有数据[4] = {0×00,0×00,0×00,0×00};
挥发性uint32_t的速度;
速度=(uint32_t的)*数据;
速度=速度×10;
数据=(uint8_t有*)的速度;


解决方案

您code不会因为在工作数据=(uint8_t有*)的速度; 你没有得到的数据是左值,你只会得到无法在转让或任何形式的算术使用数组类型。同样,速度=(uint32_t的)*数据; 是一个错误,因为只有给你数组中的第一项

你应该做的唯一正确的方法:

 挥发性uint8_t有数据[4] = {0×00,0×00,0×00,0×00};
挥发性uint32_t的速度;速度=(uint32_t的)数据[0]<< 24 |
        (uint32_t的)数据[1];&下; 16 |
        (uint32_t的)数据[2]&下;&下; 8 |
        (uint32_t的)数据[3]所述;&下; 0;速度=速度×10;数据[0] =(uint8_t有)((速度>> 24)及0xFFu);
数据[1] =(uint8_t有)((速度>> 16)及0xFFu);
数据[2] =(uint8_t有)((速度>→8)及0xFFu);
数据[3] =(uint8_t有)((速度>大于0)及0xFFu);

这是100%的便携式和明确的code。没有隐含的促销活动发生。这code不依赖于字节序或其他实现定义的行为。为什么写code,做,当你可以写code,它不?

I have a 4-byte array (data) of type uint8_t, which represents a speed data integer. I'm trying to cast this array to uint32_t integer (speed), multiply this speed by 10 and then restore it back to the 4-byte array (data). The data format is clear in the code below. I always get the error:

"assignment to expression with array type"

The code:

volatile uint8_t data[4] = {0x00 , 0x00, 0x00, 0x00};
volatile uint32_t speed;
speed=( uint32_t)*data;
speed=speed*10;
data=(uint8_t*)speed;

解决方案

Your code doesn't work because during data=(uint8_t*)speed; you don't get a "lvalue" for data, you just get an array type which can't be used in assignment or any form of arithmetic. Similarly, speed=( uint32_t)*data; is a bug because that only gives you the first item in the array.

The only correct way you should do this:

volatile uint8_t data[4] = {0x00 , 0x00, 0x00, 0x00};
volatile uint32_t speed;

speed = (uint32_t)data[0] << 24 |
        (uint32_t)data[1] << 16 |
        (uint32_t)data[2] <<  8 |
        (uint32_t)data[3] <<  0;

speed=speed*10;

data[0] = (uint8_t) ((speed >> 24) & 0xFFu);
data[1] = (uint8_t) ((speed >> 16) & 0xFFu);
data[2] = (uint8_t) ((speed >>  8) & 0xFFu);
data[3] = (uint8_t) ((speed >>  0) & 0xFFu);

This is 100% portable and well-defined code. No implicit promotions take place. This code does not rely on endianess or other implementation-defined behavior. Why write code that does, when you can write code that doesn't?

这篇关于转换的字节数组整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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