How to convert an int to a hex string?(如何将 int 转换为十六进制字符串?)
问题描述
我想将一个整数(即 <= 255)转换为十六进制字符串表示
I want to take an integer (that will be <= 255), to a hex string representation
eg: 我想传入 65
得到 'x41'
,或者 255
得到 'xff'
.
e.g.: I want to pass in 65
and get out 'x41'
, or 255
and get 'xff'
.
我试过用 struct.pack('c',
65)
来做这件事,但是 9
上面的任何东西都会窒息因为它想接收单个字符串.
I've tried doing this with the struct.pack('c',
65)
, but that chokes on anything above 9
since it wants to take in a single character string.
推荐答案
您正在寻找 chr
函数.
您似乎混合了整数的十进制表示和整数的十六进制表示,因此您需要什么并不完全清楚.根据您提供的描述,我认为其中一个片段显示了您想要的内容.
You seem to be mixing decimal representations of integers and hex representations of integers, so it's not entirely clear what you need. Based on the description you gave, I think one of these snippets shows what you want.
>>> chr(0x65) == 'x65'
True
>>> hex(65)
'0x41'
>>> chr(65) == 'x41'
True
请注意,这与 包含整数为十六进制的字符串完全不同.如果这是您想要的,请使用 hex
内置.
Note that this is quite different from a string containing an integer as hex. If that is what you want, use the hex
builtin.
这篇关于如何将 int 转换为十六进制字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 int 转换为十六进制字符串?


基础教程推荐
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01