如何为无符号整数实现 % 运算符?
how to implement the % operator for unsigned integer?
如何实现 lua 的无符号整数的 % 运算符或函数?
想过用type cast来float,但是精度是个问题
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
如何实现 lua 的无符号整数的 % 运算符或函数? 想过用type cast来float,但是精度是个问题
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