3

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?

3
  • Reopened. @q2w3e4, could you explain where you are stuck? Assign to the variable n and plug that variable into the second argument to format(). Commented Dec 29, 2020 at 13:16
  • @BradSolomon I don't know how to pass variable n to the second argument of format(). Commented Dec 29, 2020 at 13:18
  • 1
    format(6, f'0{n}b')…? Commented Dec 29, 2020 at 13:19

2 Answers 2

3

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

n = 6
format(6, f'0{n}b')
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

That seems a contorted way of doing format(n, f"0{n.bit_length()}b") and skip the import.

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.