Page 1 of 1

Separating Hex Values

Posted: Thu Nov 24, 2005 12:54 pm
by BDZ
If I have 2 hex digits (0-15) as the nibbles of one byte, what's the fastest way to retrieve those two numbers from that byte value? (I.E. 255 to 15 and 15)
Thanks.

Posted: Thu Nov 24, 2005 1:08 pm
by Z!re
look up MOD and AND and \ or /

Re: Separating Hex Values

Posted: Thu Nov 24, 2005 6:36 pm
by Guest
BDZ wrote:If I have 2 hex digits (0-15) as the nibbles of one byte, what's the fastest way to retrieve those two numbers from that byte value? (I.E. 255 to 15 and 15)
Thanks.
Ok, let's call your original byte as BYTE.
For this to work, you must do:
DIM BYTE AS INTEGER

To isolate the rightmost nibble, just remove the leftmost 4 bits by "anding" them out, like this:
RIGHTNIBBLE = BYTE AND 240

or, if you rather work with hex,
RIGHTNIBBLE = BYTE AND &HF0

To isolate the leftmost nibble, you can simulate shifting the left nibble 4 bits into the rightmost (low order) 4 bit positions by dividing the byte by 16. Dividing by 16 is the same as dividing by 2^4.
LEFTNIBBLE = BYTE / 16

*****

Posted: Thu Nov 24, 2005 6:41 pm
by moneo
The above Guest post was by me (Moneo).
Having log in problems again.
*****

Posted: Fri Nov 25, 2005 10:07 am
by Z!re

Code: Select all

LEFTNIBB = BYTE \ 16
RIGHTNIBB = BYTE MOD 16
I might have gotten the left and right wrong.. I find the above code to make more sense than using AND 240

You can replace the MOD 16 with AND 15 to gain a clock cycle or two per call.. (Note: If using FB this is done automatically, using MOD or AND doesent matter as the compiler optimize MOD n where n is a power of 2 to AND n-1)

Also, by using integer division (\) instead of floating division (/) we gain even more clock cycles as the equation ignores any decimals during evaluation..

Posted: Fri Nov 25, 2005 2:23 pm
by moneo
OOOPs :oops:
You're right Z!re, to use the AND, it should be:
RIGHTNIBBLE = BYTE AND 15

I used to do this kind of thing in assembler, which didn't have MOD.
I used the 240 because I was thinking of:
RIGHTNIBBLE = BYTE AND NOT(240)

But I screwed up.
*****

Posted: Sat Nov 26, 2005 7:26 pm
by BDZ-can't log in!
Thanks everyone! I knew the answer was simple...