简体   繁体   English

十六进制字符串到可用的十六进制字节()

[英]hexadecimal string to usable hexadecimal in bytes()

I need for my processing hexadecimals strings converted to hexadecimal.我需要将处理的十六进制字符串转换为十六进制。 I do not want to encode it.我不想对其进行编码。 Example: My progam (solving a different problem) delivers me the string result = ["0xa0", "0xb4"] .示例:我的程序(解决不同的问题)向我提供了字符串result = ["0xa0", "0xb4"] Now I want to use 0xa0 directly as a hexadecimal in bytes like bytes([result[0], results[1]) .现在我想直接使用 0xa0 作为字节的十六进制,如bytes([result[0], results[1]) But this is not possible... Does anybody know the solution?但这是不可能的......有人知道解决方案吗?

There is a fundamental confusion here, "hexadecimal" isn't a type.这里有一个基本的混淆,“十六进制”不是一种类型。 The bytes constructor takes a sequence of int objects. bytes构造函数采用一系列 int 对象。 You can convert those strings to the integer of the hexadecimal number they represent using the int constructor (by passing it the base), and passing a mapping of that operation to the bytes constructor:您可以使用int构造函数(通过将基数传递给它)将这些字符串转换为它们表示的十六进制数的 integer,并将该操作的映射传递给bytes构造函数:

>>> result = ["0xa0", "0xb4"]
>>> bytes([int(x, 16) for x in result])
b'\xa0\xb4'

I suspect that wherever you created result you used hex(x) on some int unnecessarily.怀疑无论您在何处创建result ,都不必要地在某些int上使用了hex(x) It's probably better to just not do that to begin with .最好不要一开始就这样做

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM