Converting from byte to a HEX variable

Hi
with my serial input, I am getting bytes and can print them as Serial.print(gotByte) or Serial.print(gotByte,HEX) or Serial.print(gotByte.HEX) and they print correctly.

BUT how do I convert the gotByte into a variables like gotHEX and gotDEC.
I need to "look" for certain HEX codes and then join 2 bytes (i.e."FF74") and convert the result into a value including if it is a neg or pos (2s complement)
Can Arduino do this ?
Thanks
Graham

Yes.

Post your sketch, well formated, with well-tempered comments and in so called code tags "</>" to see how we can help.

Here's part of it, conversion

//  HEX text chars are '0' to '9' and 'A' to 'F'.

if ( char >= '0' && char <= '9' )
{
  val = char - '0';
}
else if ( char >= 'A' && char <= 'F' )
{
  val = char + 10 - 'A';  //  text 'A' = hex A = decimal 10
}

There are 2 hex digits per byte, 4 bits each to assemble. Multiply the high val by 16 and add the low val to do that.

Text hex byte '37' --> decimal 3 x 16 + 7 = 55

Assume that you have entered 1234 in the InputBox of Serial Monitor with Line ending option at Newline. Arduino UNO will receive them as 0x31 0x32 0x33 0x34 and newline character as 0x0A.

Now, tell us what you want to do with the first 4-byte? Do you want to save them in a variable as 1234 (BCD coded number) or as 04D2 (hex coded natural binary number)?

char is a keyword; can it be used as a variable?

No.
You define a variable with the data type char.
char myVariable;

2 Likes

A variable is neither initialized nor assigned with a value; does Compiler allocate memory space for it?

Can you use c/c++ strtol(), and set it to base 16?

Since the conversion works as expected when using Serial.print(), you can borrow from the source code since it is freely accessible.

That first function will print the byte as hex characters, no problem. I don't think that second one will even compile. What did you mean, exactly?

Why do you want to do that, exactly? How would the variable gotByte be different to gotHEX? Remember, all variables are stored in the Arduino's memory in binary.

If you want to check that gotByte is a certain hex value such as C9, use

if (gotByte == 0xC9)

Use the standard arduino function:

int value = word(gotByteHigh, gotByteLow);
1 Like

When writing pseudocode... YES.

one of the keys to communication is figuring out where you missed not just the point but the whole pencil and never needed to take a trip to absurdity.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.