Skip to content Skip to sidebar Skip to footer

How Could I Convert A Bytes To A Whole Hex String?

a1 = b'\x01\x02\x41' \x41 is A and when I print str(a1), I get b'\x01\x02A' how could I get the original hex string? I want to get: \x01\x02\x41 I use this string for redis-cli

Solution 1:

When iterating over a bytes value, you get integers; these are trivially converted to hex notation:

def convert(value: bytes):
    return ''.join([f'\\x{b:02x}' for b in value])

Note that this produces a string with literal backslashes, x characters and hexadecimal digit characters. It is no longer a bytes value.

Demo:

>>> print(convert(b'\x01\x02\x41'))
\x01\x02\x41

Just to make sure, you do not need to worry about the bytes value. The repr() representation of a bytes object will always use ASCII characters when the byte value happens to be that of a printable ASCII codepoint. That doesn't mean the value is changed. b'\x01\x02\x41' is equal to b'\x01\x02A'. The Redis protocol doesn't know anything about \x<HH> escape sequences, so don't try to send the above string over the wire.

The escape sequences you produce are bash shell string sequences, and just like Python strings, you don't have to use escapes. As in Python, to Bash the strings "\x01\x02A" and "\x01\x02\x41" have equal values. They only make sense when you are passing in the key and value strings on the command line, not in a text file you pipe to redis-cli.

Moreover, please note that the redis-cli --pipe command takes raw Redis protocol input, not Redis command syntax, see the Redis Mass Insertion documentation. This protocol does not use \xhh sequences, as it does not use shell notation.

Instead, use the following function to generate raw SET commands:

def raw_protocol(cmd: str, *args: bytes):
    return b'\r\n'.join([
        f'*{len(args) + 1}\r\n${len(cmd)}\r\n{cmd}'.encode(),
        *(bv for a in args for bv in (b'$%d' % len(a), a)),
        b''
    ])

For a SET command, use raw_protocol('SET', keybytes, valuebytes) and write out the binary data this produces to a file opened in binary mode.


Post a Comment for "How Could I Convert A Bytes To A Whole Hex String?"