Lua: print integer as a binary

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

How can I represent integer as Binary?

so I can print 7 as 111

7条回答
  •  滥情空心
    2020-12-31 07:32

    Here is a function inspired by the accepted answer with a correct syntax which returns a table of bits in wriiten from right to left.

    num=255
    bits=8
    function toBits(num, bits)
        -- returns a table of bits
        local t={} -- will contain the bits
        for b=bits,1,-1 do
            rest=math.fmod(num,2)
            t[b]=rest
            num=(num-rest)/2
        end
        if num==0 then return t else return {'Not enough bits to represent this number'}end
    end
    bits=toBits(num, bits)
    print(table.concat(bits))
    
    >>11111111
    

提交回复
热议问题