在python中将十六进制转换为int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19819863/
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-19 14:42:22  来源:igfitidea点击:

Converting hex to int in python

pythonhexascii

提问by CMDoolittle

I am reading in 8-bit values from an ADC over USB to my computer. A python script runs on my computer and continuously displays the 8-bit values, which are in hex form. However, when the hex code corresponds to an ASCII code, python will display the ASCII character instead of the raw hex code.

我正在通过 USB 从 ADC 读取 8 位值到我的计算机。一个 python 脚本在我的计算机上运行并连续显示 8 位值,这些值是十六进制形式。但是,当十六进制代码对应于 ASCII 代码时,python 将显示 ASCII 字符而不是原始十六进制代码。

What do I need to do to the incoming data to display just the integer represented by the 8-bits? I don't want it in hex or ASCII. The problem is that the values are coming in with a slash instead of the familiar zero: '\xff' instead of '0xff'. If I go:

我需要对传入的数据做什么才能只显示由 8 位表示的整数?我不想要它在十六进制或 ASCII。问题是这些值是用斜杠而不是熟悉的零输入的:'\xff' 而不是 '0xff'。如果我走:

int('0xff',16)

the result is 255, but if I try

结果是 255,但如果我尝试

int('\xff',16)

I get an error: invalid literal for int() with base 16.

我收到一个错误:int() 以 16 为基数的无效文字。

Does anyone know of an easy way to handle the \x in the hex code (without resorting to brute force manipulation of the string)?

有谁知道处理十六进制代码中的 \x 的简单方法(无需对字符串进行蛮力操作)?

采纳答案by Joran Beasley

ord('\xff')

should give you what you want

应该给你你想要的

\x##represents a single byte or character, if you will, whereas "FF"is a string of two characters that can then be processed with int(my_string,16)but when you have a single character you probably want ord

\x##表示单个字节或字符,如果你愿意,而是"FF"一个两个字符的字符串,然后可以处理,int(my_string,16)但是当你有一个字符时,你可能想要ord

you can see this by asking something like len('\xFF')and you will see that it is only a single character

你可以通过询问类似的东西来看到这一点len('\xFF'),你会发现它只是一个字符