Understand hex bytes

I have have a CANopen Inclinometer which gives hex bytes out bytes 2 and 3 form the y
inclination and bytes 0 and 1 form X inclination as in picture shown below.


The bit I’m trying to get my head around on the Y inclination is how you add the bytes together to make 0X00 and 0X82 =130 the easy bit is you divide by 100 to 1.3 degrees and then on the X inclination 0X08 and 0x82 together to make the 3016 which is 30.16 degrees and then another example is Y inclination is 0X23 (byte 3) and byte 2 0X82 = 9090 divided by 100 = 90.99.
I’m not sure how to add the 2 bytes together to come up with 9090 in Arduino ?
Do I bit shift right or left function and by 4 or 8 ?
Thanks

int together = ((int) hbyte << 8) + lbyte;

Where hbyte and lbyte are the high and low byte you want to combine.

Cast the high byte to int and shift if you to where it needs to go. Then just add the low byte.

1 Like

This looks like an error in the table. It should read:
0082h = 130d = 1.3

Oh yeah I never noticed that.
Thank you delta_g that works perfectly and easy to understand

I'm not a fan of bit shifting signed integers. The behavior may be defined in the standard, but I'm still a little nervous of how the sign bit is treated.

Shifting left should not matter, and I would further say that the cast is not necessary.

a7

Depends on the datatype of the variable you're shifting. If you left shift a byte (uint8_t) eight places, you'll end up with zero.

It didn't for me, I'll check again when I'm.

I thought it was the same thing, all the stuff on the right hand side is done with the integer data type, that makes so many plausible expressions assigned to float types fail.

a7

This

/* Online C Compiler and Editor */
# include <stdio.h>

unsigned char xx = 0x42;
unsigned char yy = 0xde;

int main()
{
    int zz = (xx << 8) + yy;

    printf("Hello, World! 0x%x\n", zz);

    return 0;
}

Prints this

Hello, World! 0x42de

I expect C++ would do the same.

One could argue that it raises fewer questions if you put the cast in there. Same with putting syntactically unnecessary parentheses and similar extra ink.

a7