High Byte / Low Byte

Last Modified: 8/8/2022

There are many reasons why you want to get the high and low bytes of an integer, as well as break it down even further and split an integer into 4 parts (be it for getting pixel data, palette data, or other).

First, this example only works on ab integer. This is easily adaptable to work with a long variable, though.

Now, let's assume our variable, a, is set to hex value ABCD (decimal value of 43,981):

    a = &hABCD

The first thing we want to do is get the low byte. We do this by doing an And comparitor to the variable a against the maximum value of the lower byte:

    lowByte = a And &hFF

Since SecondBASIC uses 2 bytes for an integer, the maximum value would be &hFFFF. The code above would be similar to &h00FF, which when you do a binary And, you'll only get the bottom byte. To get the top byte, we have to a similar operation, but we do the maximum value of the high byte then divide the value by 1/2 of maximum bit value + 1. That sounds confusing, but I promise it's not that bad. What's half of &hFFFF? &00FF. What's &FF? 255. What's 255+1? 256! What's 256 in hexidecimal? &100!

    highByte = (a And &hFF00) / &h100

If you print out the values in hex, you'll see the high byte is equal to AB (decimal of 171), and the low byte is equal to CD (decimal of 205). Here's the full source to splitting an integer into 2 bytes:

    a = &ABCD
 
    lowByte = a And &hFF
    highByte = (a And &hFF00) / &h100
 
    Print Hex$(highByte), Hex$(lowByte)

Great! But what if we want to get each 4 bits, so you can use it for something like VdpRamRead? We do the exact same thing, except halve everything. Since you should have the core understanding of this process, I won't bother explaining it all again, but instead just show the source:

    a = &hABCD
    lowByte = a And &hFF
    highByte = (a And &hFF00) / &h100
 
    Print Hex$(highByte), Hex$(lowByte)
 
    second = highByte And &hF
    first = (highByte And &hF0) / &h10
 
    fourth = lowByte And &hF
    third = (lowByte And &hF0) / &h10
 
    Print "------------------------"
 
    Print Hex$(first)
    Print Hex$(second)
    Print Hex$(third)
    Print Hex$(fourth)