[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: manipulating bits not bytes-Enthusiasts level question
- From: Vaughan McAlley <vaughan@...>
- Date: Sun, 5 Sep 2010 00:35:49 +1000
On 4 September 2010 23:15, Patrick Mc(avery
<spell_gooder_now@spellingbeewinnars.org> wrote:
>bin_all = bin:read("*all")
This should be
bin_all = bin:read("*a")
"*all" probably triggers one line's worth instead of the whole file
> Is there also a way to convert binary to hex in pure Lua, I know Mike Pall
> has a great library but it is there a way to do this in pure Lua?
>
> Is there also a way to read one bit? read(1) is one byte, is there a way to
> read one bit?
>
> Thanks for reading-Patrick
If you have a fair bit of memory to spare:
local scratch = {}
local bins = setmetatable({}, { __index = function(t, c)
local highbit = 128
c = string.byte(c)
for i = 1, 8 do
if c >= highbit then
scratch[i] = "1"
c = c % highbit
else
scratch[i] = "0"
end
highbit = highbit / 2
end
local result = table.concat(scratch)
t[c] = result
return result
end })
local BinToHex = function(bin)
return string.gsub(bin, "[01][01][01][01]", function(b)
return string.format("%1x", tonumber(b, 2))
end)
end
local AsciiToBin = function(a)
return string.gsub(a, ".", bins)
end
print(BinToHex("01110100 00001111 11010010"))
--> 74 0f d2
a = string.char(255, 155, 55, 0)
b = AsciiToBin(a)
print(b)
--> 11111111100110110011011100000000
-- (works on long strings as well)
Vaughan