I have been playing with integer arithmetic with decimal to hex conversions
in BASIC.

Here's some code that looks like it could work, but for a couple of
reasons, *doesn't work.*

1 DEFINT B
10 H$="0123456789ABCDEF"
15 M$=""
20 B=-1
30 M$=MID$(H$,1+(B AND 15%), 1)+M$
50 B=B\16%
55 IF B=0 THEN PRINTRIGHT$("000"+M$,4):END
60 GOTO 30

-1, the integer to convert to hex, in memory looks like $FFFF. So that's
what we want to see output.

But this code outputs 000F.

That's because the way the Model T's signed integer division operator works
(maybe all integer division operators?), -1 \ 16% = 0. The purpose of
dividing by 16 is to right-shift one nibble in advance of the next
modulus/and operation to extract the low nibble.

But because of the behavior, first signed division intending to do a right
shift, is game over.

Aside from falling back to floating point... any ideas?

The code is wrong another way in that it expects after 4 shifts that the
number being converted will be zero. That works for unsigned integers. But
these are signed integers, and if negativity was preserved in the
division... that would never happen, since the quotient would always be
-1.  You'd have to count nibbles.

So, say you leverage floating point and you change line 50 to

50 B=INT(B/15)

and add a print statement,

51 PRINT M$

This gives us a sign preserving division. I don't know if it's the rounding
rule desired.

But this code will happily build a string of F's until it runs out of room.

-- John.

Reply via email to