Lua: print integer as a binary

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

How can I represent integer as Binary?

so I can print 7 as 111

7条回答
  •  余生分开走
    2020-12-31 07:36

    You write a function to do this.

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

    In Lua 5.2 you've already have bitwise functions which can help you ( bit32 )


    Here is the most-significant-first version, with optional leading 0 padding to a specified number of bits:

    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
    

提交回复
热议问题