Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
nice and fast way to convert to binary?
#1
is there a nice and fast way of converting to binary without computing powers of 2 first?

Since this number will be very large, computing powers of two would take some time..
Peace cannot be obtained without war. Why? If there is already peace, it is unnecessary for war. If there is no peace, there is already war."

Visit www.neobasic.net to see rubbish in all its finest.
Reply
#2
I actually just answered my own question:

http://www.wikipedia.org/wiki/Binary
Peace cannot be obtained without war. Why? If there is already peace, it is unnecessary for war. If there is no peace, there is already war."

Visit www.neobasic.net to see rubbish in all its finest.
Reply
#3
Dividing by two can be nice but if you want to be fast, pre-compute the powers of two... Big Grin
Antoni
Reply
#4
Not a likely option. I'll need something like 500 powers of two stored as strings..
Peace cannot be obtained without war. Why? If there is already peace, it is unnecessary for war. If there is no peace, there is already war."

Visit www.neobasic.net to see rubbish in all its finest.
Reply
#5
Store the number as a binary (each char is a power of 256)
Antoni
Reply
#6
You can try the dividing/module method:

Code:
DECLARE FUNCTION ToBin$ (Number&)
PRINT ToBin$(853847394)

FUNCTION ToBin$ (Number&)
   Res$ = ""
   WHILE Number& > 0
      Remaining& = Number& AND 1
      Res$ = LTRIM$(RTRIM$(STR$(Remaining&))) + Res$
      Number& = Number& \ 2
   WEND
   ToBin$ = Res$
END FUNCTION

Note that the AND 1 means MOD 2, that is, the remaining of dividing (Number& \ 2), but way faster Tongue. If QB had shifts, Number& = Number&\2 could be changed by Number& = Number&>>1 (shift right 1 place) which would be much faster.
SCUMM (the band) on Myspace!
ComputerEmuzone Games Studio
underBASIC, homegrown musicians
[img]http://www.ojodepez-fanzine.net/almacen/yoghourtslover.png[/i
Reply
#7
Quote:Note that the AND 1 means MOD 2, that is, the remaining of dividing (Number& \ 2), but way faster Tongue. If QB had shifts, Number& = Number&\2 could be changed by Number& = Number&>>1 (shift right 1 place) which would be much faster.

thanks for the pointer...I will try this tonight! I'll post the time savings, if they are significant![/quote]
Reply
#8
One way to improve speed would be to avoid string concatenations. For example, this code (which computes powers of 2 each time, but it's just a demo Wink ):

Code:
n% = 12345
s$ = SPACE$(8)
for i = 0 to 7
  mid$(s$, i + 1, 1) = n% and 2 ^ i
next i

print s$
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)