Hi,
I need to write a function that will convert string to binary numbers, for example if I have a string "hello" then according to ASCII its binary substitute is 01101000 01100101 01101100 01101100 01101111 (Ascii Text to Binary Converter), I think that bit32 library would be helpful. Can someone help me write this function?
local function stringToBinNumber(str)
local binarySubstitute
-- ???
return binarySubstitute
end
lua has a built in function to get the numerical representation of a character:
string.byte(str: string, index: number = 1) -> (number)
you can then manually write a function to convert said number to binary by using modulus and repetition. You could probably find something like that on stackoverflow
local function stringToBinNumber(str)
local res = ""
for letter in pairs(str:split("")) do
local byte = letter:byte()
res ..= "0" .. convert(byte) .. " "
end
return res
end
this might be scuffed but I tested it and it looks like it works:
local function convert(num: number, bits: number): (string)
local binaryNum = ""
for i = bits - 2, 0, -1 do
local temp = if bit32.band(num, 2^i) == 0 then 0 else 1
binaryNum ..= temp
end
return binaryNum
end
local function stringToBinNumber(str: string, bits: number): (string)
local res = ""
for _, letter in ipairs(str:split("")) do
local byte = letter:byte()
res ..= "0" .. convert(byte, bits) .. " "
end
return res
end
Joshument’s solution is flawless, but I’d like to share a shorter solution
local function stringToBinary(str)
return str:gsub(".", function(character)
local result = ""
for bit_index = 0, 7 do
result ..= bit32.extract(str:byte(), bit_index) -- extract will return the bit at the (bit_index+1)the position
end
return result .. " "
end):sub(1, -2) -- to remove the extra space at the end
end
The return values aren’t correct. If I want to translate “hello” your script returns this:
00010110 10100110 00110110 00110110 11110110
but it should be like this:
01101000 01100101 01101100 01101100 01101111