lua 按拉分析与合成

-- 将数值分解成bytes_table
local function decompose_byte(data)
    if not data then
        return data
    end

    local tb = {}

    if data == 0 then
        table.insert(tb, 0)
        return tb
    end

    local idx = 1
    while data > 0 do
        table.insert(tb, math.mod(data, 2))
        data = math.floor(data/2)
    end

    return tb;
end

-- 按位合成一个数值
local function synthesize_byte(bytes_table)
    local data = 0;
    for i,v in ipairs(bytes_table) do
        data = data + math.pow(2, i - 1) * bytes_table[i]
    end

    return data
end


-- 使用方法
local function show_bytes(t)
    local str = ""
    for i,v in ipairs(t) do
        str = tostring(v) .. str;
    end
    print(str)
end

local tb = decompose_byte(11)
show_bytes(tb);
print(synthesize_byte(tb))

local str = string.format("%c%c", 255, 98)
print(str, #str)

tb = decompose_byte(string.byte(str, 1))
show_bytes(tb)
print(synthesize_byte(tb))

tb = decompose_byte(string.byte(str, 2))
show_bytes(tb)
print(synthesize_byte(tb))
原文地址:https://www.cnblogs.com/emyueguang/p/3892222.html