2

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?

Ann Zen
  • 25,080
  • 7
  • 31
  • 51
q2w3e4
  • 133
  • 1
  • 5

2 Answers2

2

You can use a formatted string to dynamically insert the number n into the string:

n = 6
format(6, f'0{n}b')
Ann Zen
  • 25,080
  • 7
  • 31
  • 51
1

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

rozumir
  • 795
  • 8
  • 20
  • That seems a contorted way of doing `format(n, f"0{n.bit_length()}b")` and skip the `import`. – cdlane Jan 03 '21 at 04:41