Lua: print integer as a binary

前端 未结 7 1877
遇见更好的自我
遇见更好的自我 2020-12-31 07:11

How can I represent integer as Binary?

so I can print 7 as 111

7条回答
  •  轮回少年
    2020-12-31 07:27

    There's a faster way to do this that takes advantage of string.format, which converts numbers to base 8. It's trivial to then convert base 8 to binary.

    --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
    

    If you want to keep them all the same size, then do

    s = string.format('%.22o', n)
    

    Which gets you 66 bits. That's two extra bits at the end, since octal works in groups of 3 bits, and 64 isn't divisible by 3. If you want 33 bits, change it to 11.

    If you have the BitOp library, which is available by default in LuaJIT, then you can do this:

    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
    

    But note this only does the first 32 bits! If your number is larger than 2^32, the result wont' be correct.

提交回复
热议问题