Francis Cugler
Francis Cugler

Reputation: 7895

Combining 2 Hex Values Into 1 Hex Value

I have a coordinate pair of values that each range from [0,15]. For now I can use an unsigned, however since 16 x 16 = 256 total possible coordinate locations, this also represents all the binary and hex values of 1 byte. So to keep memory compact I'm starting to prefer the idea of using a BYTE or an unsigned char. What I want to do with this coordinate pair is this:

Let's say we have a coordinate pair with the hex value [0x05,0x0C], I would like the final value to be 0x5C. I would also like to do the reverse as well, but I think I've already found an answer with a solution to the reverse. I was thinking on the lines of using & or | however, I'm missing something for I'm not getting the correct values.

However as I was typing this and looking at the reverse of this: this is what I came up with and it appears to be working.

byte a = 0x04;
byte b = 0x0C;

byte c = (a << 4) | b;

std::cout << +c;

And the value that is printing is 76; which converted to hex is 0x4C.

Since I have figured out the calculation for this, is there a more efficient way?

EDIT

After doing some testing the operation to combine the initial two is giving me the correct value, however when I'm doing the reverse operation as such:

byte example = c;
byte nibble1 = 0x0F & example;
byte nibble2 = (0xF0 & example) >> 4;

std::cout << +nibble1 << " " << +nibble2 << std::endl;

It is printout 12 4. Is this correct or should this be a concern? If worst comes to worst I can rename the values to indicate which coordinate value they are.

EDIT

After thinking about this for a little bit and from some of the suggestions I had to modify the reverse operation to this:

 byte example = c;
 byte nibble1 = (0xF0 & example) >> 4;
 byte nibble2 = (0x0F & example);

 std:cout << +nibble1 << " " << +nibble2 << std::endl;

And this prints out 4 12 which is the correct order of what I am looking for!

Upvotes: 0

Views: 1678

Answers (1)

Pat
Pat

Reputation: 11

First of all, be careful about there are in fact 17 values in the range 0..16. Your values are probably 0..15, because if they actually range both from 0 to 16, you won't be able to uniquely store every possible coordinate pair into a single byte.

The code extract you submitted is pretty efficient, you are using bit operators, which are the quickest thing you can ask a processor to do.

For the "reverse" (splitting your byte into two 4-bit values), you are right when thinking about using &. Just apply a 4-bit shift at the right time.

Upvotes: 1

Related Questions