'===========================================================================
' Subject: DECIMAL 2 BINARY                   Date: 03-12-93 (09:14)       
'  Author: Chris Tracy                        Code: QB, QBasic, PDS        
'  Origin: DECIMAL,2,BINARY                 Packet: BINARY.ABC
'===========================================================================
'> i've got your attention, I need something VERY badly. It's a
'> relatively FAST decimal 2 binary function, as well as a binary 2
'> decimal function to go with it. The binary function needs to be
'> put in a string ($), so that I can deal with it. I'm not just

'---- Cut Here /w Sharp Razorblades ----
DECLARE FUNCTION BinDec& (Binary$)
DECLARE FUNCTION DecBin$ (decimal&)
 
Bin$ = DecBin$(5050)    ' Convert 5050 to binary
PRINT Bin$              ' Print the result
PRINT BinDec&(Bin$)     ' Convert 0001001110111010 to the decimal equiv.

FUNCTION BinDec& (Binary$) STATIC
        decimal& = 0: power% = 0
        Binary$ = UCASE$(Binary$)
        FOR i% = LEN(Binary$) TO 1 STEP -1
                digit% = ASC(MID$(Binary$, i%, 1)) - 48
                IF digit% < 0 OR digit% > 1 THEN decimal& = 0: EXIT FOR
                decimal& = decimal& + digit% * 2 ^ (power%)
                power% = power% + 1
        NEXT i%
        BinDec& = decimal&
END FUNCTION

FUNCTION DecBin$ (decimal&) STATIC
        Bin$ = ""
        h$ = HEX$(decimal&)
        FOR i% = 1 TO LEN(h$)
                digit% = INSTR("0123456789ABCDEF", MID$(h$, i%, 1)) - 1
                IF digit% < 0 THEN Bin$ = "": EXIT FOR
                j% = 8: k% = 4
                DO
                        Bin$ = Bin$ + RIGHT$(STR$((digit% \ j%) MOD 2), 1)
                        j% = j% - (j% \ 2): k% = k% - 1
                        IF k% = 0 THEN EXIT DO
                LOOP WHILE j%
        NEXT i%
        DecBin$ = Bin$
END FUNCTION

