As I'am the one who's responsible for the proper implementaion of the &B prefixed binary number strings into QB64 (
https://qb64forum.alephc.xyz/index.php?topic=1933.msg111935#msg111935), it should be probably me too, who provides an appropriate counterpart, a function to do the conversion from any given hex/oct/dec number into binary string.
Sure there are already many approaches for a Bin$ function in the Forum, some of my own, some from
@bplus and
@SMcNeill and probably others too. However, I felt there should be a function, 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 is my official Bin$ function, meant as complement to the &B notation:
- it 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 size of the input
BTW:
This update does also fix the recursion issue (
https://qb64forum.alephc.xyz/index.php?topic=4209) of the former Bin$ fucntion.
An example using this Bin$ function:Save as:
BinExample.bas (or whatever)
'=== 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 ASC(binStr$
, charPos%
) = 49: 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%
)
As it is required to preserve the UTF-8 encoding of the HTML Documentation, it is packed into an 7-zip archive file attached below. The archive does also contain the example from the codebox above.