Casting two recived bytes to an int

In my ongoing poor mans light project i will transmitt a packet of bytes from a PC to my networked arduinos. The first two bytes will be the package size, which in th PC application is casted from a short int into two bytes.

Now I want to do the same thing backwards in my arduino, casting from two bytes to an int, and things like byte order must be correct.

Can anyone advise me on this?

The data transmitted will be:

Byte 0: Message lenght LSB
Byte 1: Message lenght MSB
Byte 2: Arduino address
Byte 3-n: Data

Regards,
Tomas Sandkvist

Hi...

Can anyone advise me on this?

I imagine you'll want to use BitMath, have a read up on the link, or wait a bit longer for someone to do the work for you and post here, if you prefer. :slight_smile:

--Phil.

Well I think I've figured this out by myself:

int theResult = (int)MSB*256 + (int)LSB;

Piece of a cake!

yep, that will do it. Logical operators will also do it. I think:

int i;
byte lsb, msb;

i = (msb<<8) | lsb;

or

i = (msb<<8) + lsb;

is correct.

-j

yep, that will do it. Logical operators will also do it. I think:

int i;

byte lsb, msb;

i = (msb<<8) | lsb;



or


i = (msb<<8) + lsb;



is correct.

-j

Shifting is probably better from a performance point of view rather than multiplication of integers. If speed is an issue that is.

Shifting is probably better from a performance point of view rather than multiplication of integers. If speed is an issue that is.

I would think the runtime code is identical for both versions. The compiler is smart enough to know that multiplying by a number to the power of two is the same as shifting left by that number so it will do the shift in either case.

yep, that will do it. Logical operators will also do it.

I think it's more correct to refer to them as bitwise operators as they're not actually logical/boolean operators, see: "A word of caution: bitwise operators vs. boolean operators".

FWIW, while the multiplication approach works, I think the bitwise approach is more "standard" and it's worth familiarising oneself with it and using the approach.

--Phil.

Yes, bitwise would have been a better choice than logical. That's what happens when I post in a hurry. I was actually trying to differentiate between the boolean || and the bitwise | .

-j