splitting hexadecimal byte

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?

DataByte[0] = 0xB5

How do i separate the byte into two parts,

You do this:-

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

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.

Yeah if you nibble away at a byte you get a bit.

Grumpy_Mike:
DataByte[0] = 0xB5

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)

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

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:

B
5
FB
5

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

  a = (bar >> 4) & 0xF;

That throws away the extended sign.

1 Like

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

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.

How do i put together two bits to one byte?

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

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

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