1. From Atom to Binary Sequence
- Posted by euphoric (admin) Sep 01, 2010
- 1080 views
I want to convert a number into a sequence of bit representations. For example,
01 would convert to {0,0,0,1} 05 would convert to {1,0,1} 10 would convert to {1,0,1,0}
etc...
Doesn't the standard lib have a function for this already?
2. Re: From Atom to Binary Sequence
- Posted by mattlewis (admin) Sep 01, 2010
- 1085 views
I want to convert a number into a sequence of bit representations. For example,
01 would convert to {0,0,0,1} 05 would convert to {1,0,1} 10 would convert to {1,0,1,0}
etc...
Doesn't the standard lib have a function for this already?
Matt
3. Re: From Atom to Binary Sequence
- Posted by gaz24rip Sep 02, 2010
- 955 views
This is the code i have been useing to convert decimals numbers to binary only supports decimals numbers up to 2^32, thats 4,294,967,296 and only unsigned decimals numbers
sequence places,binary places={} for i=32 to 1 by -1 do places&=power(2,i) end for places&=1 function getlower8bits32(sequence bits) return bits[25..32] end function function gethigher8bits32(sequence bits) return bits[17..24] end function function getword32(sequence bits) return bits[17..32] end function function dec_to_binary(atom val) atom num integer step step=0 num=0 binary=repeat(0,length(places)) for i=1 to length(places) do num+=places[i] if val>=num then binary[i]=1 end if if num>val then num-=places[i] end if end for if binary[1]=1 then--overflow end if return binary[2..length(binary)] end function function binary_to_dec(sequence bits) atom num num=0 for i=1 to length(bits) do if bits[i]=1 then num+=places[ (length(places)-length(bits)) +(i)] end if end for return num end function
The in built function are much faster!
4. Re: From Atom to Binary Sequence
- Posted by SPringle Sep 03, 2010
- 914 views
There has been some discussion on this topic on the developers' list on the topic of how should bitwise functions including conversion routines should work.
As another has pointed out, using positive numbers is a nicer way of looking at bit-vectors. Whenever we have a flags value with boolean bitwise operations, we are really using a register as a bit-vector. There are limits of 32-bits which is normally enough if you ever need more than 32 you can change this:
--character attributes constant UGLY=1, STRONG=2, HAPPY=4, ...
to this:
-- character attributes constant flag_count=40 constant UGLY=int_to_bits(1,flag_count), STRONG=int_to_bits(2,flag_count), ...
The bitwise operations will work on these sequences component-wise, so you can still use for example or_bits(UGLY,STRONG) as you would with the numbers. It is wordy and inefficient as hell, but you are not limited to 32 bits.
Shawn