Posts: 3,368
Threads: 195
Joined: Jan 2003
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.
Posts: 3,368
Threads: 195
Joined: Jan 2003
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.
Posts: 1,407
Threads: 117
Joined: Dec 2002
Dividing by two can be nice but if you want to be fast, pre-compute the powers of two...
Antoni
Posts: 3,368
Threads: 195
Joined: Jan 2003
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.
Posts: 1,407
Threads: 117
Joined: Dec 2002
Store the number as a binary (each char is a power of 256)
Antoni
Posts: 6,419
Threads: 74
Joined: Mar 2002
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
. If QB had shifts,
Number& = Number&\2 could be changed by
Number& = Number&>>1 (shift right 1 place) which would be much faster.
Posts: 358
Threads: 15
Joined: May 2003
Quote:Note that the AND 1 means MOD 2, that is, the remaining of dividing (Number& \ 2), but way faster . 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]
Posts: 1,439
Threads: 15
Joined: Apr 2003
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
):
Code:
n% = 12345
s$ = SPACE$(8)
for i = 0 to 7
mid$(s$, i + 1, 1) = n% and 2 ^ i
next i
print s$