如何使用 Python 中的格式化函数将 int 格式化为长度为 n 的位串
How to format int to a bitstring of length n using format function in Python
我正在尝试使用 format
函数将 int
转换为长度为 n
的二进制字符串。我知道如何为 n
的固定值做到这一点,比如 n=3
,我想将整数 6
转换为长度为 n=3
的位串,然后我可以做 format(6, '03b')
.
我可以知道如何对任何给定的 n
做同样的事情吗?显然我做不到 format(6,'0nb')
。所以我想知道如何解决这个问题?
这个答案可能有点失误,但它使用了表示值所需的确切位数,而不是像 format(x, f"{n}b")
这样的固定值。其中 x
是一些数字,n
是位数。
import math
n = 6 # your number
format(n, f'0{int(math.log2(n))}b')
这里n
就是之前的x
这样的数字,没有n
,因为我们动态计算正确的位数来repr n
您可以使用格式化字符串将数字 n
动态插入到字符串中:
n = 6
format(6, f'0{n}b')
我正在尝试使用 format
函数将 int
转换为长度为 n
的二进制字符串。我知道如何为 n
的固定值做到这一点,比如 n=3
,我想将整数 6
转换为长度为 n=3
的位串,然后我可以做 format(6, '03b')
.
我可以知道如何对任何给定的 n
做同样的事情吗?显然我做不到 format(6,'0nb')
。所以我想知道如何解决这个问题?
这个答案可能有点失误,但它使用了表示值所需的确切位数,而不是像 format(x, f"{n}b")
这样的固定值。其中 x
是一些数字,n
是位数。
import math
n = 6 # your number
format(n, f'0{int(math.log2(n))}b')
这里n
就是之前的x
这样的数字,没有n
,因为我们动态计算正确的位数来repr n
您可以使用格式化字符串将数字 n
动态插入到字符串中:
n = 6
format(6, f'0{n}b')