Continue readingBinary Magic with Signed Integers"/> Skip to content

Binary Magic with Signed Integers

In binary the high bit (the one immediately following the &b in Xojo code) is the “sign bit”. When it’s set to 1, the value is interpreted as “negative” and when it’s set to 0, the value is “positive”. Meaning that bit is not used as part of the “number” itself.

So if we start counting up values are written as:

1 => &b00000001
2 => &b00000010
3 => &b00000011

and so on until we get to:

127 => &b01111111

Now, what’s the “next number”? That would be:

&b10000000

which this code:

Dim i As Int8 = &b10000000

tells you is -128.

What does -128 look like in something like an Int16?

Dim i8 As Int8 = &b10000000
Dim i16 As Int16 = i8

System.DebugLog(Bin(i8)) // <<< shows 10000000
System.DebugLog(Bin(i16)) // <<< shows 1111111110000000

Why is the int16 have all those 1’s at the beginning? It’s because if you assign:

Dim i16 As Int16 = &b1000000000000000

you’ll find that this is -32768 or the smallest value an Int16 can hold. When you assign a little value like -128 the “lowest” 8-bit can be copied from the int8 form and the upper 8 bits have to be copies of the “sign bit” – that first one after the “&b”.

This is called sign extension and is required when you move a smaller type into a larger one — like moving an Int8 into an Int16 or an Int8 into an Int32.

Failing to do this for signed values (i.e. if the code did something like “fill the upper part with 0s”):

Dim i8 As Int8 = &b10000000
System.DebugLog(Bin(i8))

Dim i16 As Int16 = &b0000000010000000
System.DebugLog(Bin(i16))

would have the Int8 value saying it held -128 and the Int16 saying it held 128 (note the sign change!) and this would totally wreck trying to do any math.

Remember this is all necessary in order to manage the sign of an integer. It is not necessary with unsigned types such as UInt8, UInt16, etc.