[REBOL] Re: Converting numbers to binary form.
From: carl:cybercraft at: 10-Sep-2002 19:38
On 10-Sep-02, alan parman wrote:
> I want the following...
> 1 ==> 00000001
> 2 ==> 00000010
> 3 ==> 00000011
> 4 ==> 00000100
> ...
> 255 ==> 11111111
> 256 ==> 100000000
> ...
> 1000 ==> 11111010000
> 1001 ==> 11111010001
Checking on binary in the REBOL guide, the simpliest way to achieve
this seems to be by using enbase and to-binary...
>> to-hex 256
== #00000100
>> enbase/base to-binary [1] 2
== "00000001"
>> enbase/base to-binary [2] 2
== "00000010"
>> enbase/base to-binary [3] 2
== "00000011"
>> enbase/base to-binary [255] 2
== "11111111"
A problem arises when you want to go above 1 byte though, as this
doesn't work...
>> enbase/base to-binary [256] 2
== "00000000"
you having to use two integers in the block to get the desired
results...
>> enbase/base to-binary [1 0] 2
== "0000000100000000"
>> enbase/base to-binary [1 1] 2
== "0000000100000001"
>> enbase/base to-binary [255 255] 2
== "1111111111111111"
A function using that method might be...
base-2: func [n [integer!]][
enbase/base to-binary reduce [to-integer n / 256 n // 256] 2
]
which gives...
>> base-2 0
== "0000000000000000"
>> base-2 1
== "0000000000000001"
>> base-2 2
== "0000000000000010"
>> base-2 3
== "0000000000000011"
>> base-2 255
== "0000000011111111"
>> base-2 256
== "0000000100000000"
>> base-2 257
== "0000000100000001"
>> base-2 65535
== "1111111111111111"
Obviously that's restricted to 16 bits and includes them all in the
string, but the function could be easily altered to suit your
specific needs.
HTH.
--
Carl Read