Home > Software design >  Is there way to print python3 bytes as hex string without ascii conversion and without using a loop?
Is there way to print python3 bytes as hex string without ascii conversion and without using a loop?

Time:12-30

buf = b"\x00\xdd\x41"

print(str(buf))

gives '\x00\xddA'.

I need '\x00\xdd\x41'.

Basically Show hex value for all bytes, even when ASCII characters are present without the loop or external module. Just want to know if this is possible with any built-in Python3 function.

My current code is "".join(["\\x" hex(x)[2:] for x in buf]). I am trying to find a built-in alternative to it, if it exists in Python 3 or any simpler alternative to it.

CodePudding user response:

you can use this format:

buf = b"\x00\xdd\x41"
hex_string = "\\x".join("{:02x}".format(b) for b in buf)
print(hex_string)  # output: '\x00\xdd\x41'

CodePudding user response:

There's no built-in function that does what you want.

What do you consider "not a loop"? There's a hidden loop in the non-Python implementation of re.sub below, but no Python loop.

import re

def hexify(s):
    return "b'"   re.sub(r'.', lambda m: f'\\x{ord(m.group(0)):02x}', buf.decode('latin1'))   "'"

buf = b'\x00\xdd\x41'
print(hexify(buf))

Output:

b'\x00\xdd\x41'
  • Related