Mailing List Archive: 49091 messages
  • Home
  • Script library
  • AltME Archive
  • Mailing list
  • Articles Index
  • Site search
 

Binary to Decimal Function

 [1/3] from: ptretter::charter::net at: 25-Aug-2000 22:52


Librarian comment

Or use this script to convert any base to any other base: base convert 

Here is a useful function for anyone needing to convert binary digits to decimal. Took me awhile but here it is: bnfunc: func [ "Convert Binary digits to Decimal equivalent" bn [string!] "The binary representation" /local holder count][ holder: make integer! 0 reverse bn count: length? bn for x 1 count 1 [ if (to-string (pick bn x)) = "1" [ holder: (2 ** (x - 1)) + holder ] ] return holder ] Let me know what you think. I am gonna create some refinements to enhance it a bit. Paul Tretter

 [2/3] from: kgd03011:nifty:ne:jp at: 26-Aug-2000 18:56


Hi Paul, You should copy the argument before you reverse it, since reverse will change the original data:
>> a: "1000"
== "1000"
>> bnfunc a
== 8
>> a
== "0001" Instead of reverse bn you could say reverse bn: copy bn Also, an easier way to do if (to-string (pick bn x)) = "1" [ ... ] is if ((pick bn x)) = #"1" [ ... ] Here's another way to do the whole thing: from-bin: func [ {convert a binary string representation into a numeric value} b [string!] /local x ][ x: 0.0 foreach bit b [ x: x * 2 + either #"1" = bit [1][0] ] x ] Eric ===================== Here is a useful function for anyone needing to convert binary digits to decimal. Took me awhile but here it is: bnfunc: func [ "Convert Binary digits to Decimal equivalent" bn [string!] "The binary representation" /local holder count][ holder: make integer! 0 reverse bn count: length? bn for x 1 count 1 [ if (to-string (pick bn x)) = "1" [ holder: (2 ** (x - 1)) + holder ] ] return holder ] Let me know what you think. I am gonna create some refinements to enhance it a bit. Paul Tretter

 [3/3] from: ptretter:charter at: 26-Aug-2000 8:30


I love this list. Excellent feedback. Your function is very small and efficient. Very nice. Paul Tretter