This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
JJRcop's profile picture

Simple binary conversion function.

Started by JJRcop, 28 March 2013 - 01:54 PM
JJRcop #1
Posted 28 March 2013 - 02:54 PM
Just a simple function to convert an unsigned byte into its bit pattern. Give it a number from 0-255 and it will give you a binary sequence for that number.

You can use string.byte() with a UTF-8 compatible character to get its byte.

Also included an extremely simple reconversion function for convenience.



function dec2Bin(dec)
dec=dec*2
local bin=""
  for i=0,7 do
   bin=bin..tostring(math.ceil(math.floor(dec/2)%2))
   dec=math.floor(dec/2)
  end
return string.reverse(bin)
end

function bin2Dec(bin)
  return tonumber(bin, 2)
end

It's really small at 9 lines, but here is a pastebin if that is too hard for you. pastebin get h4aa5CWr

Now you can have fun with saving and reading binary from files. Even tighter data compression!
robhol #2
Posted 28 March 2013 - 09:16 PM
Does this do anything that the Bit API doesn't?

Also, the math.ceil isn't needed, since an integer (from math.floor) % an integer will always return an integer.
theoriginalbit #3
Posted 28 March 2013 - 09:43 PM
Does this do anything that the Bit API doesn't?

Also, the math.ceil isn't needed, since an integer (from math.floor) % an integer will always return an integer.
The bit API no longer has bit.tobits so yes it does something it doesn't do…
As of ComputerCraft 1.42 the bit library has moved to Java code, and as such this function is no longer required or included.
JJRcop #4
Posted 29 March 2013 - 01:13 AM
Oh. To be honest I have never heard of the Bit API until now, sorry. Oh well, guess it was removed.
Also, thanks. I guess the math.ceil is unnecessary, but I'll keep it there for safety's sake.
(You know, I want my program to work even if one of the laws of math suddenly change and it ends up not being an integer.)

And I'm guessing that the Bit API is/was java side so this is just a Lua implementation of the converter, which is the hard part.
theoriginalbit #5
Posted 29 March 2013 - 01:18 AM
the bit library exists still. its only the toBits function that has been removed.
JJRcop #6
Posted 29 March 2013 - 01:20 AM
Ah, alright. So this is useful!
Alright I'm going to admit this. I put the math.ceil there because it feels wrong to me to assume math is going to output an integer.
robhol #7
Posted 29 March 2013 - 02:32 AM
(You know, I want my program to work even if one of the laws of math suddenly change and it ends up not being an integer.)

Yeah, it's a real bitch when that happens. :3
FuuuAInfiniteLoop(F.A.I.L) #8
Posted 01 April 2013 - 10:46 AM
How ca i adapt it to work with numbers from 1 to 128?
theoriginalbit #9
Posted 01 April 2013 - 04:06 PM
How ca i adapt it to work with numbers from 1 to 128?
Are you talking about when you put decimal numbers 1-128 or from bases 1 - 128?