Lua: print integer as a binary

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

How can I represent integer as Binary?

so I can print 7 as 111

7条回答
  •  太阳男子
    2020-12-31 07:28

    This maybe not work in lua that has no bit32 library

        function toBinary(number, bits)
            local bin = {}
            bits = bits - 1
            while bits >= 0 do --As bit32.extract(1, 0) will return number 1 and bit32.extract(1, 1) will return number 0
                           --I do this in reverse order because binary should like that
                table.insert(bin, bit32.extract(number, bits))
                bits = bits - 1
            end
            return bin
        end
        --Expected result 00000011
        print(table.concat(toBinary(3, 8)))
    

    This need at least lua 5.2 (because the code need bit32 library)

提交回复
热议问题