如何在 Python 中舍入十六进制值



我有一个简单的算法可以找到 2 个十六进制值之间的差异,我正在尝试找到一种将值四舍五入的方法。

例如,如果值为 0x7f8000,我想将其四舍五入为 0x800000。

这可能吗?

除了

以十六进制格式打印十六进制数字外,没有其他特殊处理方法。

>>> 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)

入始终可以通过添加比块大小小的内容来完成,然后将块大小的所有尾随数字设置为零。

在您的情况下,如果要向上舍入到 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

最新更新