Separating Hex Values

If you have questions about any aspect of QBasic programming, or would like to help fellow programmers solve their problems, check out this board!

Moderators: Pete, Mods

Post Reply
BDZ
Coder
Posts: 49
Joined: Sun Nov 20, 2005 5:41 pm
Location: Wisconsin
Contact:

Separating Hex Values

Post 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.
Z!re
Veteran
Posts: 887
Joined: Wed Aug 04, 2004 11:15 am

Post by Z!re »

look up MOD and AND and \ or /
I have left this dump.
Guest

Re: Separating Hex Values

Post 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

*****
moneo
Veteran
Posts: 451
Joined: Tue Jun 28, 2005 7:00 pm
Location: Mexico City, Mexico

Post by moneo »

The above Guest post was by me (Moneo).
Having log in problems again.
*****
Z!re
Veteran
Posts: 887
Joined: Wed Aug 04, 2004 11:15 am

Post 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..
I have left this dump.
moneo
Veteran
Posts: 451
Joined: Tue Jun 28, 2005 7:00 pm
Location: Mexico City, Mexico

Post 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.
*****
BDZ-can't log in!

Post by BDZ-can't log in! »

Thanks everyone! I knew the answer was simple...
Post Reply