Search code examples
pythonbinarydata-conversion

How to format int to a bitstring of length n using format function in Python


I am trying to convert an int to a binary string of length n using format function. I know how to do it for a fixed value of n, say n=3 and I want to convert integer 6 to a bitstring of length n=3, then I can do format(6, '03b').

May I know how to do the same for any given n? Clearly I cannot do format(6,'0nb'). So I'm wondering how to solve this?


Solution

  • This answer is maybe a little misspoint but it use exact number of bit that are necessary to represent value, not a fixed value like format(x, f"{n}b"). Where x is some number, and n is number of bits.

    import math
    
    n = 6 # your number
    format(n, f'0{int(math.log2(n))}b')
    

    Here n is the number like x before, and there is no n, because we dynamicaly calculate right number of bits to repr n