简体   繁体   中英

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"] . Now I want to use 0xa0 directly as a hexadecimal in bytes like 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. 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:

>>> 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. It's probably better to just not do that to begin with .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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