Qbasicnews.com

Full Version: Need binary to decimal help!
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
My binary to decimal converter won't work. I've tried multiple ways and multiple methods and it's always flawed.

Code:
CLS
INPUT "Enter binary binary number", binary1$
length = LEN(binary1$)
t = length + 1
g = -1
DO
t = t - 1
z = z + 1
g = g + 1
IF length = 1 THEN t = 1
b$ = MID$(binary1$, t, t)
IF b$ = "1" THEN b1 = 1: result = b1 * (2 ^ g)
decimal1 = decimal1 + result
IF z = length THEN EXIT DO
LOOP
PRINT decimal1

Can anyone help? It messes up when I get to number 101. Thanks!
Lets try running through "01":

The first time through, b$ = "1", so result gets set to 1 (1 * 2^0), which gets added into decimal1, so now decimal1 is 1.

The second time through, b$ = "0", so result goes unchanged (still 1), which get added into decimal1... <- There's your problem.
I helped him on MSNM he didn't know FOR NEXT could go backwards. which really helps


[syntax="QBASIC"]DECLARE FUNCTION dec2bin$ (dec!)
DECLARE FUNCTION bin2dec! (bin$)
CLS
PRINT "Binary: "; dec2bin$(13)
PRINT "Decimal: "; bin2dec("1101")






FUNCTION bin2dec (bin$)
a = 1
FOR i = LEN(bin$) TO 1 STEP -1
IF MID$(bin$, i, 1) = "1" THEN dec = dec + a
a = a * 2
NEXT
bin2dec = dec
END FUNCTION

FUNCTION dec2bin$ (dec)
DO
bin$ = LTRIM$(STR$(dec MOD 2)) + bin$
dec = INT(dec / 2)
LOOP UNTIL dec = 0
dec2bin$ = bin$
END FUNCTION[/syntax]
thx guys!
I am a bit late here. Buf if you want a really fast bin2dec function, you can create a lookup table for powers of 2. Thats the only clue I can post for now. Gotta go party!! Big Grin