Paul Bernard
Paul Bernard

Reputation: 1

Weird byte conversion in python

I have a function converting integers to bytes and ran into the following issue.

When using the code below.

>>> data = 9

>>> print(data.to_bytes())

I get this :

>>> b'\t'

When I should be getting this:

b'\x09'

Can anyone say this is happening?

Upvotes: -2

Views: 84

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48693

If you want the hex value, you can use an f-string:

data = 9

print(f"b'\\x{data:02x}'")  # b'\x09'

If you want a hex dump, you can try:

#!/usr/bin/env python3

data = 9
bytes = data.to_bytes(2, 'little')

print(' '.join(f"{byte:02x}" for byte in bytes))  # '09 00'

Here is a version that shows a hex dump for an encoded message:

#!/usr/bin/env python3

import logging


# Ad-hoc version of itertools.batched
# https://docs.python.org/3/library/itertools.html#itertools.batched
def batched(lst, n):
    """
    Batch data from the list into chunks of length n.
    The last chunk may be shorter than n.

    :param lst: List to be divided into chunks.
    :param n: Size of each chunk.
    :return: Generator yielding chunks of size n.
    """
    for i in range(0, len(lst), n):
        yield lst[i:i + n]


# Uses f-strings to format bytes into hex
def hex_dump_1(data):
    """
    Generate a hex dump for the given bytes.

    :param data: Bytes to be dumped.
    :return: Hex dump string.
    """
    return '\n'.join(' '.join(f"{byte:02x}" for byte in chunk) for chunk in batched(data, 16))


# Chunks the bytes.hex() result
def hex_dump_2(data):
    """
    Generate a hex dump for the given bytes (alternative).

    :param data: Bytes to be dumped.
    :return: Hex dump string.
    """
    return '\n'.join(' '.join(batched(chunk, 2)) for chunk in batched(data.hex(), 32))


if __name__ == '__main__':
    # Configure logging
    logging.basicConfig(format='[%(levelname)s] %(asctime)s %(message)s', level=logging.DEBUG)

    # Test message
    message = 'Hello World, this is a test!'
    byte_data = str.encode(message)
    
    # Log hex dump (first approach)
    logging.debug(f"Hex dump 1:\n\n{hex_dump_1(byte_data)}\n")
    
    # Log hex dump (second approach)
    logging.debug(f"Hex dump 2:\n\n{hex_dump_2(byte_data)}\n")

Output:

Hex dump:

48 65 6c 6c 6f 20 57 6f 72 6c 64 2c 20 74 68 69
73 20 69 73 20 61 20 74 65 73 74 21

Upvotes: 0

Related Questions