1

I'm in a special circumstance where I would like to convert an integer into a bytes object of the smallest length possible. I currently use the following method to covert to bytes:

number = 9847
bytes = number.to_bytes(4, 'little')

However I would like to scale that the amount of bytes used down (the 4) to the smallest possible size. How can I achieve this?

2 Answers 2

2

You can get an exact conversion without needing to use log arithmetic yourself by querying the int for how many bits it needs for its value like so:

import math

def convert(i: int) -> bytes:
    return i.to_bytes(math.ceil(i.bit_length() / 8))
Sign up to request clarification or add additional context in comments.

Comments

1

I figured it out on my own! I use the following function to do the conversion to bytes for me now:

import math

def int_to_bytes(self, integer_in: int) -> bytes:
    """Convert an integer to bytes"""
    # Calculates the least amount of bytes the integer can be fit into
    length = math.ceil(math.log(integer_in)/math.log(256))

    return integer_in.to_bytes(length, 'little')

This works because with exponents a = b^e is equivalent to e = log(a)/log(b)

In this case our problem is integer_in = 256^e, and we want to solve for e. This can be solved by rephrasing it to e = log(integer_in)/log(256). Lastly, we use math.ceil() to round up the answer to an integer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.