tags:

views:

101

answers:

2

Hi guys, 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

+2  A: 
ArunSaha
This answer is incorrect, at least for C. `buf[0]<<8` promotes `buf[0]` to `int` and performs the bitshift as an `int`.
R..
A: 

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.

R..