简体   繁体   English

将unsigned char> 255转换为int

[英]converting unsigned char > 255 to int

I'm programming with a PLC and I'm reading values out of it. 我正在用PLC编程,我正在读取它的价值。

It gives me the data in unsigned char . 它为我提供了unsigned char的数据。 That's fine, but the values in my PLC can be over 255. And since unsigned chars can't give a value over 255 I get the wrong information. 这很好,但我的PLC中的值可能超过255.由于无符号字符不能给出超过255的值,我得到错误的信息。

The structure I get from the library: 我从图书馆得到的结构:

struct PlcVarValue
{
    unsigned long   ulTimeStamp         ALIGNATTRIB;
    unsigned char   bQuality            ALIGNATTRIB;
    unsigned char   byData[1]           ALIGNATTRIB;
};
  • ulTimeStamp gives the time ulTimeStamp给出了时间
  • bQuality gives true/false (be able to read it or not) bQuality给出真/假(能否读取或不读)
  • byData[1] gives the data. byData[1]给出了数据。

Anyways I'm trying this now: (where ppValues is an object of PlcVarValue ) 反正我现在尝试此:(其中ppValues是一个对象PlcVarValue

    unsigned char* variableValue =  ppValues[0]->byData;            
    int iVariableValue = *variableValue;

This works fine... untill ppValues[0]->byData is > 255; 这很好用......直到ppValues[0]->byData > 255;

When I try the following when the number is for example 257: 当我尝试以下数字时,例如257:

unsigned char testValue = ppValues[0]->byData[0];
unsigned char testValue2 = ppValues[0]->byData[1];

the output is testvalue = 1 and testvalue2 = 1 输出为testvalue = 1testvalue2 = 1

that doesn't make sense to me. 这对我没有意义。

So my question is, how can I get this solved so it gives me the correct number? 所以我的问题是,我怎样才能解决这个问题,以便给出正确的数字?

That actually looks like a variable-sized structure, where having an array of size 1 at the end being a common way to have it. 这实际上看起来像一个可变大小的结构,其中最后有一个大小为1的数组是获得它的常用方法。 See eg this tutorial about it . 参见例如本教程

In this case, both bytes being 1 for the value 257 is the correct values. 在这种情况下,值257两个字节都是1是正确的值。 Think of the two bytes as a 16-bit value, and combine the bits. 将这两个字节视为16位值,并将这些位组合在一起。 One byte will become the hight byte, where 1 corresponds to 256 , and then add the low bytes which is 1 and you have 256 + 1 which of course is equal to 257 . 一个字节将成为高字节,其中1对应于256 ,然后添加低字节,即1 ,你有256 + 1 ,当然等于257 Simple binary arithmetic. 简单的二进制算术

Which byte is the high, and which is the low we can't say, but it's easy to check if you can force a message that contains the value 258 instead, as then one byte will still be 1 but the other will be 2 . 哪个字节是高,哪个是我们不能说的低,但很容易检查是否可以强制包含值258的消息,因为那时一个字节仍然是1但另一个将是2

How to combine it into a single unsigned 16-bit value is also easy if you know the bitwise shift and or operators: 如果您知道按位移位和/或运算符,如何将它组合成单个无符号16位值也很容易:

uint8_t high_byte = ...
uint8_t low_byte = ...
uint16_t word = high_byte << 8 | low_byte;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM