Question

If I receive a message via RS232 consisting of 2 Byte length, e.g. 0000 0001 0001 1100 (that is 100011100, lsb on the right), I wanna save it to a variable called value.

I am "decoding" the byte stream with this step:

rxByte = Serial1.read()

messageContent[0] = rxByte

messageContent[1] = rxByte

with the first rxByte having the value 0000 0001 and the second 0001 1100. Or are those values already converted internally to HEX or DEC?

Now I have seen code that saves it this way to value:

uint32_t value = messageContent[0] *256 + messageContent[0]

How does this work?

Was it helpful?

Solution

messageContent[0] *256 is essentially a bitshift: the code is equivelent to (and more readable as)

uint32_t value = (messageContext[0]) << 8 + messageContent[1];

So if `messageContent[0] = 0x01' and messageContext[2] = 0x1C

value = (0x01 << 8)+0x1C
value = (0x0100)+0x1C
value = 0x011C

Works find, but depending on the endianess of your machine, it is equivalent to:

 uint32_t value = *((uint16_t*)(messageContext));

OTHER TIPS

Decoding procedure:

//char messageContent[2]; //Always keep in mind datatypes in use!!!
messageContent[0] = Serial1.read()
messageContent[1] = Serial1.read()

Way you were doing was placing same value in both positions.

If you want to read both bytes into a 16-bit or bigger integer:

short int messageContent = Serial1.read()<<8+Serial.read();

Or are those values already converted internally to HEX or DEC?

Data is always binary. Hex or Dec is just its representation. You say "variable x as a value of 123" - this is a human interpretation, actually variable x is a block of memory comprised of some bytes which are by themselves groups of 8 bits.

Now I have seen code that saves it this way to value:

uint32_t value = messageContent[0] *256 + messageContent[0]

That's like I tell you 45 thousands and 123, so you build your number as 45*1000+123=45123. 256 is 2^8, equal to a full byte, b'1 0000 0000'.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top