Go Down

Topic: splitting hexadecimal byte (Read 1 time) previous topic - next topic

HULK

I did a search but could not find the answer, probably due to me using the wrong terminology.

Searching for a way to split a hexadecimal byte array into two parts.
Let´s say i have the hexadecimal byte as stated below in a array.
DataByte[0] = 0xB5

How do i separate the byte into two parts,
DataParts[0] = 0xB
DataParts[1] = 0x5

Would the itoa() function do it?

Grumpy_Mike

DataByte[0] = 0xB5

Quote
How do i separate the byte into two parts,


You do this:-

DataParts[0] = DataByte[0] >> 4
DataParts[1] = DataByte[0] & 0xf

HULK

Thanks a lot, will test that feedback!
Side note, after some more reading i found out that one part of a byte is a nibble, did not know that.


Nick Gammon

Yeah if you nibble away at a byte you get a bit.
http://www.gammon.com.au/electronics

crimony


DataByte[0] = 0xB5

Quote
How do i separate the byte into two parts,


You do this:-

DataParts[0] = DataByte[0] >> 4
DataParts[1] = DataByte[0] & 0xf


Won't that do sign extension on DataParts[0] of the type of DataByte[] is char? (ie. result in DataParts[0] == 0xF5)

Nick Gammon

Well, you said "byte array" rather than "char array". Try this:

Code: [Select]
void setup ()
{
  Serial.begin (115200);
  byte a, b;

  byte foo = 0xB5;
  a = foo >> 4;
  b = foo & 0xF;
 
  Serial.println (a, HEX);
  Serial.println (b, HEX);

  char bar = 0xB5;
  a = bar >> 4;
  b = bar & 0xF;
 
  Serial.println (a, HEX);
  Serial.println (b, HEX);
}

void loop () {}


Output:

Code: [Select]
B
5
FB
5


You are right, it sign-extends (the B not the 5). But you could do:

Code: [Select]
  a = (bar >> 4) & 0xF;

That throws away the extended sign.
http://www.gammon.com.au/electronics

HULK

What about doing it the other way?

DataParts[0] = 0xB
DataParts[1] = 0x5

How do i put together two bits to one byte?
DataByte[0] = 0xB5

WizenedEE

Well you have a collection of bits that look something like this:
00001001
00000111

So if you just moved the 1's out of the way on one of the numbers (bitshift left), you'd get this:
00001001
01110000

Then, since there is only one "1" in each column, you can either add or bitwise-OR them together to get a combined byte.

Grumpy_Mike

Quote
How do i put together two bits to one byte?

DataByte[0] = (DataParts[0] << 4) | DataParts[1]

HULK

All worked as expected, case closed.
Thanks for the help, hope it helps someone else !


floresta

Quote
How do i put together two bits to one byte?

Just to keep everything correct I think you meant "How do I put together two nibbles to one byte?"

Don

Go Up