为了提高可读性,我想打印一个由4个(半字节)组成的二进制数,用下划线分隔。
例如:
9 => "1001"
60 => "0011_1100"
100 => "0110_0100"
63000 => "1111_0110_0001_1000"
我想知道是否有一种简单的方法可以做到这一点?
答案 0 :(得分:5)
将逻辑拆分为生成4组并加入。
def gen(x):
while x:
yield bin(x % 16)[2:].zfill(4)
x >>= 4
def nibble(x):
return "_".join(gen(x))
答案 1 :(得分:2)
尝试:
def bin_nibble(val):
b = bin(val)[2:]
new_b = '_'.join([b[::-1][i:i+4][::-1] for i in range(0, len(b), 4)][::-1])
如果您想添加前导零:
def bin_nibble(val):
b = bin(val)[2:]
new_b = '_'.join([b[::-1][i:i+4][::-1] for i in range(0, len(b), 4)][::-1])
return ''.join(['0']*(4 - len(b) % 4 if len(b) % 4 != 0 else 0) + [new_b])
答案 2 :(得分:1)
从最高到最低:
def binNibble(num):
nibb = bin(num)[2:]
k = 0 if len(nibb)%4 == 0 else 4-len(nibb)%4 # needs zeros?
nibb = "0"*k + nibb # add them here
return '_'.join(nibb[i:i+4] for i in range(0,len(nibb),4) ) # put _ in
for i in range(0,1152,127):
print(i,": ",binNibble(i))
输出:
0 : 0000
127 : 0111_1111
254 : 1111_1110
381 : 0001_0111_1101
508 : 0001_1111_1100
635 : 0010_0111_1011
762 : 0010_1111_1010
889 : 0011_0111_1001
1016 : 0011_1111_1000
1143 : 0100_0111_0111
您的示例:
9 : 1001
60 : 0011_1100
100 : 0110_0100
63000 : 1111_0110_0001_1000
答案 3 :(得分:0)
我已经提出了这个功能:
import math
def bin_nibble(val):
num_bits = len(format(val, "b"))
return "_".join(reversed([format((val>>shift*4)&0x0F, "04b")
for shift in range(math.ceil(num_bits/4))]))
答案 4 :(得分:0)
使用str.format
的另一种方法:
def bin_nibble(a, pad=4):
b = '{:b}'.format(a)
if len(b) % pad:
b = '0' * (pad - (len(b) % pad)) + b
return '_'.join(b[k:k+pad] for k in range(0, len(b), pad))
tests = [9, 60, 100, 63000]
for k in tests:
print(bin_nibble(k))
输出:
1001
0011_1100
0110_0100
1111_0110_0001_1000
答案 5 :(得分:0)
@Tjaart ,根据您的输入和预期输出,以下代码将按预期工作。
如果您的任何输入失败,请尝试并告诉我。
"""
INPUTS AND EXPECTED OUTPUTS:-
9 => "1001"
60 => "0011_1100"
100 => "0110_0100"
63000 => "1111_0110_0001_1000"
"""
def get_binary(n):
s = bin(n)[2:]; # Getting binary string
strs = [];
while s:
l = len(s); # Finding lenght of binary string
if l > 4:
strs.insert(0, s[l-4:]);
s = s[:l-4];
else:
l = len(s);
s = "0"*(4-l) + s; # If length is not equal to 4 (modify it by adding 0s to front)
strs.insert(0, s);
s = "";
return "_".join(strs);
# EXAMPLE 1
a = 9;
print(get_binary(a)); # 1001
# EXAMPLE 2
b = 60;
print(get_binary(b)); # 0011_1100
# EXAMPLE 3
c = 100;
print(get_binary(c)); # 0110_0100
# EXAMPLE 4
d = 63000;
print(get_binary(d)); # 1111_0110_0001_1000