简体   繁体   中英

uint8_t to uint16_t

How do you convert a uint8_t to a uint16_t?

currently im breaking down uint16_t to uint8_t like this:

    packetBuffer.header[0] = ((co2Val>>8) & 0xff);
    packetBuffer.header[1] = (co2Val & 0xff);
    packetBuffer.header[2] = ((humVal>>8)&0xff);
    packetBuffer.header[3] = (humVal & 0xff);
    packetBuffer.header[4] = ((tempVal>>8)&0xff);
    packetBuffer.header[5] = (tempVal & 0xff);

co2Val,humVal and tempVal are all uint16_t

however, i'll need to change them back to get the corresponding value. This is received at the other end as uint8_t buf[16].

this is how i did it:

    CO2Val = (buf[0]<<8)|buf[1];
    HumVal = (buf[2]<<8)|buf[3];
    HumVal = (HumVal & 0x0fff);
    TempVal = (buf[4]<<8)|buf[5];
    TempVal = (TempVal & 0x3fff);

The results are different. Anyone know why? thanks

How do you convert a uint8_t to a uint16_t?

By simply assigning:

uint8_t  val_u8  = ...
uint16_t val_u16 = val_u8;

I think that the question you wanted to ask is "how do you combine uint_8 to a uint_16?"

I am guessing that you may have problem in the line

 
 
 
  
  CO2Val = (buf[0]<<8)|buf[1];
 
  

if buf[ 0 ] is uint8_t . Cast it to uint16_t before doing the bit-shift to ensure room for the 8 bits (or else, the bits would "fall off" the MSB edge)

 
 
 
  
  uint16_t CO2Val = ( (uint16_t) buf[0] << 8) | buf[1];
 
  

My guess is that you're really using C++, not C, and the buf[0]<<8 etc. are exhibiting undefined behavior due to the shift size being at least the width of the type. In C, this would not happen, since arithmetic operands are always promoted at least to int .

Anyway, let's try some simpler, more legible code:

packetBuffer.header[0] = co2Val/256;
packetBuffer.header[1] = co2Val;
packetBuffer.header[2] = humVal/256;
packetBuffer.header[3] = humVal;
packetBuffer.header[4] = tempVal/256;
packetBuffer.header[5] = tempVal;

and:

CO2Val = buf[0]*256+buf[1];
HumVal = buf[2]%16*256+buf[3];
TempVal = buf[4]%64*256+buf[5];

I've left in place your truncation of the upper bits of HumVal and TempVal , but it might be better practice to instead check for out-of-range values and issue an error of some sort.

Edit: Since OP clarified that the language is C, I'm unsure what is wrong. It seems we're still missing information. Perhaps looking at a dump of the buffers involved would be informative.

Not sure what you mean when you say " how do you combine uint_8 to a uint_16?" What does this statement mean ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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