Log In  

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

P#101661 2021-12-06 21:22

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
P#101663 2021-12-06 21:46
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

P#101693 2021-12-06 23:14 ( Edited 2021-12-06 23:29)
1

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

P#101734 2021-12-07 00:48
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.

P#101849 2021-12-07 06:18 ( Edited 2021-12-07 06:19)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-04-19 15:51:11 | 0.017s | Q:19