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

时间:2018-04-16 08:18:03

标签: python hex rounding

我有一个简单的算法,可以找到2个十六进制值之间的差异,我试图找到一种方法来舍入值。

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

这甚至可能吗?

2 个答案:

答案 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