将整数转换为特定格式的十六进制字符串
我是 python 新手,有以下问题:我需要将整数转换为 6 个字节的十六进制字符串。
例如 281473900746245 --> "\xFF\xFF\xBF\xDE\x16\x05"
十六进制字符串的格式很重要。 int 值的长度是可变的。
格式“0xffffbf949309L”对我不起作用。 (我用 hex(int-value) 得到这个)
我的最终解决方案(经过一些“玩”)是:
def _tohex(self, int_value):
data_ = format(int_value, 'x')
result = data_.rjust(12, '0')
hexed = unhexlify(result)
return hexed
感谢您的所有帮助!
I am new to python and have following problem: I need to convert an integer to a hex string with 6 bytes.
e.g.
281473900746245 --> "\xFF\xFF\xBF\xDE\x16\x05"
The format of the hex-string is important. The length of the int value is variable.
The format '0xffffbf949309L' don't work for me. (I get this with hex(int-value))
My final solution (after some "playing") is:
def _tohex(self, int_value):
data_ = format(int_value, 'x')
result = data_.rjust(12, '0')
hexed = unhexlify(result)
return hexed
Thank you for all the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可能有更好的解决方案,但您可以这样做:
细分:
更新:
根据@multipleinstances和@Sven的评论,由于您可能正在处理长值,因此您可能需要调整十六进制的输出一点点:
但是,有时,十六进制的输出可能是奇数长度,这会破坏解码,因此最好创建一个函数来执行此操作:
There might be a better solution, but you can do this:
Breakdown:
Update:
Per @multipleinstances and @Sven's comments, since you might be dealing with long values, you might have to tweak the output of hex a little bit:
Sometimes, however, the output of hex might be an odd-length, which would break decode, so it'd probably be better to create a function to do this:
在 Python 3.2 或更高版本中,您可以使用
to_bytes()< /code>
整数方法。
In Python 3.2 or above, you can use the
to_bytes()
method of the interger.如果您不使用 Python 3.2(我很确定您不使用),请考虑下一个方法:
If you don't use Python 3.2 (I'm pretty sure you don't), consider the next approach: