在 Python 中将整数转换为 2 字节的十六进制值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16742022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:31:15  来源:igfitidea点击:

Convert an integer to a 2 byte Hex value in Python

pythonpython-2.7inthexdata-conversion

提问by Brett Prudhom

For a tkinter GUI, I must read in a Hex address in the form of '0x00' to set an I2C address. The way I am currently doing it is by reading the input as a string, converting the string to an integer, then converting that integer to an actual Hex value as shown in the partial code below:

对于 tkinter GUI,我必须以“0x00”的形式读取十六进制地址以设置 I2C 地址。我目前的做法是将输入作为字符串读取,将字符串转换为整数,然后将该整数转换为实际的十六进制值,如下面的部分代码所示:

GUI initialization:

图形界面初始化:

self.I2CAddress=StringVar()
self.I2CAddress.set("0x00") #Sets Default value of '0x00'
Label(frame, text="Address: ").grid(row=5, column=4)
Entry(frame, textvariable=self.I2CAddress).grid(row=5, column=5)

Then inside the function:

然后在函数内部:

addr = self.I2CAddress.get()   
addrint = int(addr, 16)  
addrhex = hex(addrint)

This works for most values, but my issue is that if I enter a small Hex value string such as '0x01', it converts to the proper integer of 1, but then that is converted to a Hex value of 0x1 instead of 0x01.

这适用于大多数值,但我的问题是,如果我输入一个小的十六进制值字符串,例如“0x01”,它会转换为正确的整数 1,但随后会转换为十六进制值 0x1 而不是 0x01。

I am an EE and have very limited programming experience, so any help is greatly appreciated.

我是一名 EE,编程经验非常有限,因此非常感谢任何帮助。

采纳答案by Martijn Pieters

Use the format()function:

使用format()功能

format(addrint, '#04x')

This formats the input value as a 2 digit hexadecimal string with leading zeros to make up the length, and #includes the 'standard prefix', 0xin this case. Note that the width of 4 includes that prefix. xproduces lower-case hex strings; use Xif you need uppercase.

这将输入值格式化为带有前导零的 2 位十六进制字符串以构成长度,并且在这种情况下#包括“标准前缀” 0x。请注意,宽度 4 包括该前缀。x产生小写的十六进制字符串;使用X如果您需要大写。

Demo:

演示:

>>> for i in range(8, 12):
...     print format(i, '#04x')
... 
0x08
0x09
0x0a
0x0b