Hey Everyone,
I stumbled upon this (possibly very simple) problem, and I can't get over it: How do I convert a binary number (let's say, a string "0101") to a decimal integer number?
The opposite, from dec to binary, is easy, but I really couldn't find in the help files a way (or think of an easy way) to convert from binary to decimal...
Thanks!
0.set total=0
1. set var=1
2. look at the rightmost binary digit and if it=1 add var to total
3. repeat 2, but each time look one more digit to the left and multiply var by 2
Does this work...
binstring:String = "011100"
val=1
For x = 0 To binstring.length
total = total + Int(Mid(binstring , binstring.length - x , 1)) * val
Print total + " " + val
val = val * 2
Next
?
As a function...
SuperStrict
Print bin2dec("010011100")
Function bin2dec:Int(binval:String)
Local Val:Int = 1
Local total:Int
For Local x :Int= 0 To binval.length
total :+ Int(Mid(binval , binval.length - x , 1) ) * Val
' debuglog Int(Mid(binval, binval.length - x , 1)) + " * " + val + " = " + total
val = Val * 2
Next
Return total
End Function
Let BMax do all the hard work for you...
Local binary$ = "10101010"
Print Int("%" + binary$)Print BinToDec("10101010")
End
Function BinToDec(binary$)
If binary$[0] <> 37 Then binary$ = "%" + binary$
Return Int(binary$)
End Function
Ooo didnt know you could do that Yan
Hey, thanks!
Last night when I posted I was thinking of doing a function like the ones Nomen and Tony suggested, but I thought there should be a way built in BlitzMax.
One thing, though: I didn't understand why the variable can't be "37" in the function Yan posted. Is it something like a special character code?
Thanks a lot!
Leo.
Chr(37) = %
Yan,
very cool! I also did not know you could do it that way
It is pretty handy. :o)
Mark made a post showing this method not long after BMax's release...So I stoled it... ;o)