q2w3e4
q2w3e4

Reputation: 305

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?

Upvotes: 3

Views: 569

Answers (2)

rozumir
rozumir

Reputation: 905

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

Upvotes: 2

Red
Red

Reputation: 27577

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

n = 6
format(6, f'0{n}b')

Upvotes: 3

Related Questions