First post, by Peter Swinkels
Curious as to how floating points exactly work internally (suprisingly despite all my years of programming I've never really gotten into that in depth) I wrote these two programs in QBasic:
This is a tiny experiment where the user can define the four hexadecimal bytes that make up a single precision floating point and then view the result:
DEFINT A-ZRESTORE hexesbin$ = ""FOR byt = 0 TO 3READ hx$hxv = VAL("&H" + hx$)bin$ = CHR$(hxv) + bin$NEXT bytCLSPRINT CVS(bin$)ENDhexes:DATA "3F": REM Sign (0x80) + scale.DATA "80": REM Exponent mbs (0x80) + mantisse.DATA "00": REM Mantisse.DATA "00": REM Mantisse.
And this is a program which allows the user to specify a single precision floating point and view its inner structure in binary:
DEFINT A-ZDECLARE SUB disect (flt AS SINGLE)CLSdisect -1SUB disect (flt AS SINGLE)bin$ = MKS$(flt)byte1 = ASC(MID$(bin$, 1, 1))byte2 = ASC(MID$(bin$, 2, 1))byte3 = ASC(MID$(bin$, 3, 1))byte4 = ASC(MID$(bin$, 4, 1))mant1 = byte1mant2 = byte2mant3 = (byte3 AND &H7F)exponentmbs = ABS(((byte3 AND &H80) <> 0))scale = (byte4 AND &H7F)sign = ((byte4 AND &H80) <> 0)totalmantisse& = mant1 + (mant2 * 256&) + (mant3 * 65536)totalexponent = scale + (exponentmbs * 128)PRINT "Sign: Scale: Exponent mbs: Mant 3: Mant 2: Mant 1:"PRINT USING " ### ### ### ### ### ###"; sign; scale; exponentmbs; mant3; mant2; mant1PRINT totalmantisse&PRINT totalexponentEND SUB
Please note that these programs are experimental and that I haven't fully tested everything yet.
If you notice a bug or mistake, you are of course welcome to let me know. 😀
Oh, and why QBasic? I felt like doing a bit of retro-programming at the same time and at this moment I am specifically curious about floating points in older BASIC dialects.
My GitHub:
https://github.com/peterswinkels