gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:25:13 25 4
gpt4 key购买 nike

我有一个简单的算法可以找到 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)

关于python - 如何在 Python 中舍入十六进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49852583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com