Author Topic: convert decimal to binary  (Read 12763 times)

dan

  • Newbie
  • Posts: 47
    • View Profile
convert decimal to binary
« 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

Dogface

  • Newbie
  • Posts: 33
  • Woof$
    • View Profile
Re:convert decimal to binary
« Reply #1 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

Dogface

  • Newbie
  • Posts: 33
  • Woof$
    • View Profile
Re:convert decimal to binary
« Reply #2 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