你写了一个函数来做到这一点.
num=7
function toBits(num)
-- returns a table of bits, least significant first.
local t={} -- will contain the bits
while num>0 do
rest=math.fmod(num,2)
t[#t+1]=rest
num=(num-rest)/2
end
return t
end
bits=toBits(num)
print(table.concat(bits))
Run Code Online (Sandbox Code Playgroud)
在Lua 5.2中,你已经有了可以帮助你的按位功能(bit32)
这是最重要的第一个版本,可选的前导0填充到指定的位数:
function toBits(num,bits)
-- returns a table of bits, most significant first.
bits = bits or math.max(1, select(2, math.frexp(num)))
local t = {} -- will contain the bits
for b = bits, 1, -1 do
t[b] = math.fmod(num, 2)
num = math.floor((num - t[b]) / 2)
end
return t
end
Run Code Online (Sandbox Code Playgroud)
有一种更快的方法可以利用 string.format 将数字转换为基数 8。然后将基数 8 转换为二进制是微不足道的。
--create lookup table for octal to binary
oct2bin = {
['0'] = '000',
['1'] = '001',
['2'] = '010',
['3'] = '011',
['4'] = '100',
['5'] = '101',
['6'] = '110',
['7'] = '111'
}
function getOct2bin(a) return oct2bin[a] end
function convertBin(n)
local s = string.format('%o', n)
s = s:gsub('.', getOct2bin)
return s
end
Run Code Online (Sandbox Code Playgroud)
如果你想让它们保持相同的大小,那么做
s = string.format('%.22o', n)
Run Code Online (Sandbox Code Playgroud)
这让你得到 66 位。最后是两个额外的位,因为八进制以 3 位为一组工作,而 64 不能被 3 整除。如果您想要 33 位,请将其更改为 11。
如果你有BitOp库,它在 LuaJIT 中默认可用,那么你可以这样做:
function convertBin(n)
local t = {}
for i = 1, 32 do
n = bit.rol(n, 1)
table.insert(t, bit.band(n, 1))
end
return table.concat(t)
end
Run Code Online (Sandbox Code Playgroud)
但请注意,这只适用于前 32 位!如果您的数字大于 2^32,则结果将不正确。