Log In  


function dtb(num)
local bin=""
for i=1,8do
bin..=flr(num/2^(8-i))%2
end
return bin
end



1

Token-optimized

function dtb(num)
  local bin=""
  for i=7,0,-1do
    bin..=num\2^i %2
  end
  return bin
end

if you need 16-bit bin, this is one token bigger, but can handle it:

function dtb2(num)
  local bin=""
  for i=1,16 do
    bin=num %2\1 ..bin
    num>>>=1
  end
  return bin
end

1

This might be something to have in future Pico-8, the ability to convert to binary thus:

TOSTR(VAL, [FORMAT_FLAGS])

print(tostr(254,3))

11111110

You can do the function with BAND too if you like, that's how I do it:

function dtb2(num)
local bin=""
for i=0,7 do
  bin..=band(num,2^i)\2^i
end
return bin
end

28-tokens


1

operator '&' is preferred to function 'band' nowadays (see release thread from version where binary operators were added)


1

Don't mind me, @merwok. I'm old school. :)

Given the chance I'd open that line up:

  pow=2^i
  ban=band(num,pow)
  dig=int(ban/pow)
  bin=bin..dig

I know there are shortcuts, sometimes legibility is important - at least for me.



[Please log in to post a comment]