In relation to my previous post, I learned a bit about bits and whatnot, but there’s an issue I’ve come across.
Whenever I insert a number like 0110 1010 into tostring, it removes all zeroes before the first integer that isn’t a zero. So 0001 1001 would come out as 1 1001 since it removes it. This is an issue because I use string.split to split and manage the bit operations in my module. This is the first function where I accounted an issue.
--- @param binary : number
-- converts the operator sign on the given binary code to negative or positive
function binaryBit.operator(binary : number, length : number)
if ( not length ) or #tostring(binary) < length or #tostring(binary) - 1 > length then return 'invalid conversion...' end
local str = string.split(tostring(binary), "")
local function splitToNum(str)
local newstr = ""
for _,num in pairs(str) do
newstr ..= num
end
end
if ( not str[length + 1] ) then table.insert(str, "1") return splitToNum(str), 'negative' end
if ( str[length + 1] == '1' ) then table.remove( str, length + 1 ) return splitToNum(str), 'positive' end
end
A quick explanation was, I read all numbers in the supposed “length” of the binary data and turned it negative or positive by adding a Boolean basically (1 or 0) to the end of the data.
If you want strings to be formatted specifically, try using string.format. It lets you pad out numbers with 0s as you want.
local bitCount = 8 -- Example length
local num = 00011001
-- Putting 0 before the size for %d will pad with zeroes.
-- In this case, I could have done just "%08d" for the format string,
-- but I wanted it to be dynamic.
print(string.format("%0" .. bitCount .. "d", num)) -- will print "00011001"
But also, you might want to look into the bit32 library. And two’s complement. And, for what it’s worth, you should know that num = 00011001 makes eleven thousand and one, not 25.