Internet PLC Forum

General => Technical support => Topic started by: dan on March 22, 2007, 08:14:56 AM

Title: convert decimal to binary
Post by: dan on March 22, 2007, 08:14:56 AM
Hi,

What is the easiest way I can convert a decimal no to binary?
(using a custom function)

Dan
Title: Re:convert decimal to binary
Post by: Dogface on March 22, 2007, 11:08:56 PM
That was fun!

try this:
'x=number to convert to binary
'a$=binary number in string format

'To convert a decimal number to binary, first subtract the largest possible power of two.
'Keep subtracting the next largest possible power from the remainder, marking 1s in each column
'where this is possible and 0s where it is not.

'add statements for each power of two until you have covered the maximum size number you need to convert

a$=""
y=128 'using 128 you can convert any whole decimal number < 256 to binary
for z=1 to 8
if x>-1 then a$=a$+"1":x=x-y
else a$=a$+"0"
endif
y=y/2
next

Hope this helps
Dogface
Title: Re:convert decimal to binary
Post by: Dogface on March 22, 2007, 11:11:36 PM
sorry made a mistake there:


a$=""
y=128 'using 128 you can convert any decimal number < 256 to binary
for z=1 to 8
if x-y>-1 then a$=a$+"1":x=x-y
else a$=a$+"0"
endif
y=y/2
next