我有一个简单的算法,可以找到2个十六进制值之间的差异,我试图找到一种方法来舍入值。
例如,如果值为0x7f8000,我想将其四舍五入为0x800000。
这甚至可能吗?
答案 0 :(得分:3)
>>> def myroundup(n, step):
... return ((n - 1) // step + 1) * step
...
>>> hex(myroundup(0x7f8000, 0x10000))
'0x800000'
>>> myroundup(998000, 10000) # works with other bases too
1000000
如果你需要四舍五入,请使用:
>>> def myrounddn(n, step):
... return n // step * step
为了完整性,舍入到最接近的步骤:
>>> def myround(n, step):
... return (n + step // 2) // step * step
您也可以使用myrounddn
定义:
>>> def myround(n, step):
... return myrounddn(n + step // 2, step)
答案 1 :(得分:3)
总是可以通过添加一个小于块大小的东西来完成舍入,然后将块大小的所有尾随数字设置为零。
在您的情况下,如果您想要向上舍入 n 尾随十六进制零,请使用:
def round_to_n_trailing_zeros_in_hex(v, n):
trailing_bits = ((1<<(n*4))-1)
# ^^^ this is 0b11111111111111111111 == 0x000fffff for n = 5
return (v + trailing_bits) & ~trailing_bits