Search code examples
pythonpython-3.xcastingintegerbyte

How to cast bytes to an int and back to the same bytes?


I have an arbitrary byte in Python that I want to cast into a 64 bit integer and back into the same byte.

I am currently, using this to turn the bytes into an int, where x is a byte I am given:

int.from_bytes(x, "little")

But I'm struggling on how to use int.to_bytes() to convert it back to the same bytes because I'm unsure what to put for length, nothing seems to create the equivalent byte?


Solution

  • I may not understand you question, but consider this:

    x = b'deadbeef'
    print(f'x -> {x}')    # x -> b'deadbeef'
    
    i = int.from_bytes(x, 'little')
    print(f'i -> {i:,}')  # i -> 7,378,415,037,781,730,660
    
    y = i.to_bytes(len(x), 'little')
    print(f'y -> {y}')    # y -> b'deadbeef'
    
    
    # If you don't know the original variable, you can compute the byte length
    # like this:
    
    bit_length = i.bit_length() + 1  # Including sign bit.
    byte_length = (bit_length + 7) // 8
    
    z = i.to_bytes(byte_length, 'little')
    print(f'z -> {z}')    # z -> b'deadbeef'