_TITLE "Quick BIN$ test" 'b+ 2020-03-02 QB64 v1.4 < important for testing &B numbers
INPUT "Enter a number to convert to test BIN$ > ", test&&
'Function: Convert any given dec/hex/oct number into a binary string.
' Can handle positive and negative values and works in that
' similar to the QB64 built-in HEX$ and OCT$ functions.
'
'Synopsis: binary$ = BIN$ (value&&)
'
'Result: binary$ --> The binary representation string of the given
' number without leading zeros for positive values
' and either 8/16/32 or 64 chars for negatives,
' depending on the input size.
'
'Inputs: value&& --> The pos./neg. number to convert, may also be
' given as &H or &O prefixed value.
'
'Notes: You may also pass in floating point values, as long as its
' represented value fits into the _INTEGER64 (&&) input, hence
' approx. -9.223372036854776E+18 to 9.223372036854776E+18.
' Different from HEX$ and OCT$, BIN$ won't throw an overflow
' error, if this range is exceeded, but the result is probably
' wrong in such a case.
'---------------------------------------------------------------------
'--- option _explicit requirements ---
DIM temp~&&
, charPos%
, highPos%
'--- init ---
temp~&& = value&&
BIN$
= STRING$(64, "0"): charPos%
= 64: highPos%
= 64 '--- convert ---
IF (temp~&&
AND 1) THEN MID$(BIN$
, charPos%
, 1) = "1": highPos%
= charPos%
charPos% = charPos% - 1: temp~&& = temp~&& \ 2
'--- adjust negative size ---
IF -value&&
< &H0080000000~&&
THEN highPos%
= 33 IF -value&&
< &H0000008000~&&
THEN highPos%
= 49 IF -value&&
< &H0000000080~&&
THEN highPos%
= 57 '--- set result ---
BIN$
= MID$(BIN$
, highPos%
)