Lua:打印整数作为二进制

fl0*_*00r 11 binary lua

如何将整数表示为二进制?

所以我可以打印7111

jpj*_*obs 9

你写了一个函数来做到这一点.

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)

  • 您的函数中有反转位,因此“20”将返回“00101”,而不是“10100” (2认同)
  • 您没有说明您想要大端还是小端。这个例子也没有泄露它,因为 111 是一个回文;)。无论如何,调整它很容易:只需使用 `nBits=ceiling(select(2,math.frexp(num)))` 并使用从 nBits 开始到 1 的 for 循环。 (2认同)

Hou*_*ter 7

有一种更快的方法可以利用 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,则结果将不正确。