BinToDec() Function

Blitz3D Forums/Blitz3D Beginners Area/BinToDec() Function

_PJ_(Posted 2010) [#1]
This function is supposed to translate a binary string i.e. "111010010000110111" into its equivalent integer.
However, certain values (I think those over 16-bit size) are not returned correctly, and I'm stuck at how to fix it...

Here's the code:



Floyd(Posted 2010) [#2]
The following function should work. It just picks "0" and "1" out of the string and stuffs the corresponding 0 and 1 bits into an integer.

Function BinToDec%(sBinary$)
	For n = 1 To Len( sBinary )
		bit = Mid( sBinary, n, 1 )
		dec = ( dec Shl 1 ) Or bit
	Next
	Return dec
End Function



_PJ_(Posted 2010) [#3]
I think I started with something similar, Dunno what I did to not get that working right! You made it seem so simple, shows what I get for overcomplicating the matter! Thanks very much, yet again, Floyd!


Charrua(Posted 2010) [#4]
be careful with sBinary strings with more than 31 characters, if there are some diferent to "0" then you will get an unspected result and the bit shift of "ones" far away from 32 will be discardes (as integers in blitz are 32 bits long)
I recomend to test if Len(sBinary) is more than 31 and if is 32 only acept the string if the most significant character is "0", if it is "1" then a negative number will be returned.

if your sBynary strings are all of fewer chars than 32 then, simply ignore my advice.

Juan


_PJ_(Posted 2010) [#5]
Yeah good point, Charrua. I reimplemented the len() check and removed the left extraneous chars, a string>32 length would fail anyway, so restricting to just 4 bytes works best I think - simulating the kinda 'rollover' you'd get with other stuff