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

Advanced Bit Functions

Started by byPhins, 29 October 2015 - 09:03 PM
byPhins #1
Posted 29 October 2015 - 10:03 PM
Functions :

- bits.tobit(Number) – Convert Number to bit
- bits.tonum(bit) – Convert bit to Number
- bits.bittotext(bit) – Converts Bits to Text(string)
- bits.texttobit(string) – Converts Text(string) to Bits

How to install :

- pastebin get kusciurg bits
- os.loadAPI("bits")

READY!
Creator #2
Posted 30 October 2015 - 08:34 AM
If everyone's first program was so useful the forums would be a better place. By the way do you use tostring? (The func) eat +1
H4X0RZ #3
Posted 30 October 2015 - 01:19 PM
Looks nice! +1

First of all there is a small misunderstanding in the OP. A character isn't represented by a "bit" but by a "byte". Or, to be more precise, 7 bits (at least the displayable characters for CC).


Other than that you can make it much smaller by using some simple optimizations. (I don't want to sound rude or anything. I just want to point out some "easier" ways to achieve what you are doing right now so you can learn from that)
1. You can define the base you want tonumber to convert to. (It will default to base 10) That means you don't have to write a special "algorithm" which converts a string into binary.
2. There is no need for this giant "ascii" function. You can convert characters from/to numbers (which can be converted to binary) easily using string.char (number->char) and string.byte (char->number)
3. You can make your split function a bit smaller by using the "or" operator. You can set dinp to " dinp or '.' " and it will either use dinp if the user entered it or default to ".".

Here is an example (taken from some code I wrote a while ago)

function split(str,reg)
	    local tbl = {}
	    for match in string.gmatch(str,reg or ".") do
			    table.insert(tbl,match)
	    end
	    return tbl
end

function numberToBinary(number)
  local s = ""
  repeat
	local remainder = number % 2
	s = remainder..s
	number = (number-remainder)/2
  until number==0
  return s
end
function binaryToNumber(bin)
		return tonumber(bin,2)
end

function charToBinary(ch)
		return numberToBinary(string.byte(string.sub(ch,1,1)))
end

function binaryToChar(bin)
		return string.char(binaryToNumber(bin))
end
Edited on 30 October 2015 - 12:21 PM