BIN$ (binary converter)Contributor(s):
@RhoSigmaSource: qb64.org Forum
URL:
https://www.qb64.org/forum/index.php?topic=4261.msg136393#msg136393Tags: [binary] [number conversion]
Description:
Although there are already many approaches for a BIN$ function in the Forum, some of my own, some from bplus and Steve McNeill and probably others, I felt there should be one, which best mimics the regular behavior and results of the built-in HEX$ and OCT$ functions, rather than focusing on speed or extended flexibility.
So here it is:
can handle positive and negative numbers
returns the binary string without &B prefix, just as HEX$ and OCT$ do
the result for positive numbers is just as long as needed, ie. no leading zeros are returned
the result length for negative numbers is determined by the integer range, which the given input number does fit in, eg. 8 for numbers in _BYTE range (down until -128), 16 for INTEGER (down until -32768) etc..Source Code:
'=== Full description for the Bin$() function is available
'=== in the separate HTML document.
'=====================================================================
'-- some usage examples
PRINT "some simple numbers..." num&
= 5:
PRINT num&;
"= "; Bin$
(num&
) num&
= -4:
PRINT num&;
"= "; Bin$
(num&
) num&
= 32000:
PRINT num&;
"= "; Bin$
(num&
)
PRINT "works also with &B, &H and &O..." PRINT " &B1101 = "; Bin$
(&B1101
) PRINT " &H211 = "; Bin$
(&H211) PRINT " &O377 = "; Bin$
(&O377)
PRINT "and even with floating points (converts integer part only)..." num#
= 123.456:
PRINT num#;
"= "; Bin$
(num#
) num#
= -60000.25:
PRINT num#;
"= "; Bin$
(num#
) num#
= 0.5:
PRINT num#;
"= "; Bin$
(num#
)
'-- done
'--- Full description available in separate HTML document.
'---------------------------------------------------------------------
'--- option _explicit requirements ---
DIM temp~&&
, binStr$
, charPos%
, highPos%
'--- init ---
temp~&& = value&&
binStr$
= STRING$(64, "0"): charPos%
= 64: highPos%
= 64 '--- convert ---
IF (temp~&&
AND 1) THEN MID$(binStr$
, 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$(binStr$
, highPos%
)
Librarian's note: RhoSigma is author of the &B updates to QB64, and this BIN$ should serve as best complement to &B thus the replacement of the old BIN$ code; screenshot contains new range of numbers that this BIN$ can do.