Re: From Atom to Binary Sequence

new topic     » goto parent     » topic index » view thread      » older message » newer message

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!

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu