加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

lua – 如何为无符号整数实现%运算符?

发布时间:2020-12-14 21:44:01 所属栏目:大数据 来源:网络整理
导读:如何为lua的无符号整数实现%运算符或函数? 我想过使用类型转换来浮动,但精度是一个问题. function ModU(a,b) if b == 0 then return a end if a == 0 then return 0 end if b 0 then if a 0 then if a b then return b-a else return a end else return a
如何为lua的无符号整数实现%运算符或函数?
我想过使用类型转换来浮动,但精度是一个问题.

function ModU(a,b)
    if b == 0 then return a end
    if a == 0 then return 0 end

    if b < 0 then
        if a < 0 then
          if a < b then return b-a 
          else return a 
          end
       else 
          return a
       end
    else
        if a > 0 then return math.tointeger(a % b) 
        else 
            i = ModU(x & 0x7fffffff + 1,b)
            j = ModU(2^31 - 1,b)
            return ModU(i + j,b)
        end
    end
end

解决方法

function unsigned_mod(x,y)
   return y<=x and x<0 and x-y or y<0 and x or ((x>>1)%y*2+(x&1)-y)%y
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读