Lua:将整数打印为二进制 [英] Lua: print integer as a binary

查看:939
本文介绍了Lua:将整数打印为二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I represent integer as Binary?

所以我可以将7打印为111

推荐答案

您编写了一个函数来执行此操作.

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

在Lua 5.2中,您已经具有按位功能可以帮助您( bit32 )

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

这是最重要的优先版本,可选的前导0填充到指定的位数:

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

这篇关于Lua:将整数打印为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆