Advertisement

How do i chop a byte in half?

Started by July 26, 2000 12:44 AM
3 comments, last by SikCiv 24 years, 5 months ago
For a WORD, I use HIBYTE and LOBYTE to seperate the hi and lo bytes. How do I do the same for a BYTE? Obviously I can only do this by dumping the results into 2 seperate BYTES. I guess the fastest way (and it needs to be fast) would be to use the & or | operators, but i dont know how to use them to that extent. I know i need to mask the un-needed 4 bits to 0, but how exactly do i do this? My guess... byte1 = origbyte | 0x0F; byte2 = origbyte | 0xF0; Is this the way to do it?

  Downloads:  ZeroOne Realm

You are close. Try this instead...

byte1 = origbyte & 0x0F;
byte2 = origbyte & 0xF0;

This will chop off the high nibble for byte1 and the low nibble for byte2.

Since you don't understand | and & very well. I'll explain them quickly.

The | operator is the "or" operator. This means that if either bit is 1, it will give you 1. Obviously, this won't mask your bits since any original bit that is 1 will come out 1.

The & operator is the "and" operator. This means that boths bits have to be 1 to return 1. So, as long as the mask has a 0 bit in it, the bit at that position will be 0. If the mask has a 1 bit, then the bit at that position will be the original bit.

Edited by - I-Shaolin on July 26, 2000 2:13:48 AM
Advertisement
You both are close, maybe this:

byte1 = origbyte & 0x0F;
byte2 = (origbyte & 0xF0) >> 4;

so, how about:
    #define LOBITS(byte) ((byte) & 0x0F)#define HIBITS(byte) (((byte) & 0xF0) >> 4)#define MAKEBYTE(lo,hi) ((lo) | ((hi) << 4))    


But be sure the vars for the MAKEBYTE are 0 <= var <= 15.
You can mask rest out, but this is faster

Thanks, ill try them out...



But wouldnt the >> and 0xF0 clash in
"byte2 = (origbyte & 0xF0) >> 4;"
It would be the same as "byte1 = origbyte & 0x0F";

But what do i know..im just guessing.




  Downloads:  ZeroOne Realm

No, the >> 4 makes sure the output value is in the least significant nibble of the output byte (?).

Say you have this byte:

byte = 01101110

Low nibble = byte & 0x0F comes out to 00001110

High nibble, if you had byte & 0xF0 would come out to 01100000, but you need to shift it by 4 so that it comes out as 00000110.

That way, you have the actual value of ONLY the high nibble, and not the original byte, minus the low nibble.

I hope this was clear.

Edited by - Qoy on July 26, 2000 3:01:48 AM

This topic is closed to new replies.

Advertisement