You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lua 5.1环境下64位数字位运算适配Poly1305算法求助

受限Lua 5.1环境下的64位位运算实现方案(适配Poly1305移植)

核心思路是将64位数值拆分为高32位和低32位两个无符号整数,用{high, low}的表结构存储,所有运算基于bit32库对两个32位分量操作,完全规避双精度浮点数的精度丢失问题。


基础64位位运算实现

1. 64位与运算(AND)

local function bit64_and(a, b)
    return {
        high = bit32.band(a.high, b.high),
        low = bit32.band(a.low, b.low)
    }
end

分别对高、低32位执行与运算,结果组合为新的64位结构。

2. 64位或运算(OR)

local function bit64_or(a, b)
    return {
        high = bit32.bor(a.high, b.high),
        low = bit32.bor(a.low, b.low)
    }
end

分别对高、低32位执行或运算,结果组合为新的64位结构。

3. 64位异或运算(XOR)

local function bit64_xor(a, b)
    return {
        high = bit32.bxor(a.high, b.high),
        low = bit32.bxor(a.low, b.low)
    }
end

分别对高、低32位执行异或运算,结果组合为新的64位结构。

4. 64位左移运算(SHL,无符号)

local function bit64_shl(a, n)
    if n <= 0 then return a end
    if n >= 64 then return {high=0, low=0} end

    if n <= 32 then
        -- 低位左移溢出的n位作为高位的进位
        local carry = bit32.extract(a.low, 32 - n, n)
        return {
            high = bit32.bor(bit32.lshift(a.high, n), carry),
            low = bit32.lshift(a.low, n)
        }
    else
        -- 左移超过32位,原低位成为高位,低位清零
        n = n - 32
        return {
            high = bit32.lshift(a.low, n),
            low = 0
        }
    end
end

5. 64位右移运算(SHR,无符号)

local function bit64_shr(a, n)
    if n <= 0 then return a end
    if n >= 64 then return {high=0, low=0} end

    if n <= 32 then
        -- 高位右移溢出的n位作为低位的进位
        local carry = bit32.extract(a.high, 0, n)
        return {
            high = bit32.rshift(a.high, n),
            low = bit32.bor(bit32.rshift(a.low, n), bit32.lshift(carry, 32 - n))
        }
    else
        -- 右移超过32位,原高位成为低位,高位清零
        n = n - 32
        return {
            high = 0,
            low = bit32.rshift(a.high, n)
        }
    end
end

6. 64位无符号加法

local function bit64_add(a, b)
    local low_sum = a.low + b.low
    -- 提取低32位加法的进位(0或1)
    local carry = bit32.rshift(low_sum, 32)
    -- 保留低32位有效数据
    local low = bit32.band(low_sum, 0xFFFFFFFF)
    -- 高位相加并加上进位,再保留高32位有效数据
    local high = bit32.band(a.high + b.high + carry, 0xFFFFFFFF)
    return { high = high, low = low }
end

适配Poly1305的扩展处理

Poly1305核心运算涉及130位整数的模运算(mod (2^130 - 5)),可基于上述64位运算进一步实现多精度整数操作:

  1. 将130位数值拆分为4个32位分量(高位补0凑齐128位,剩余2位单独处理或合并到最高分量);
  2. 基于64位加法实现多精度加法;
  3. 基于64位乘法+加法实现多精度乘法;
  4. 最后实现针对2^130 -5的模运算逻辑。

内容的提问来源于stack exchange,提问作者neth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 02:18:16