转换为二进制文件并保持Python中前导零

我试图使用Python中的bin()函数将整数转换为二进制。 但是,它总是删除我实际需要的前导零,使得结果始终为8位:

例:

bin(1) -> 0b1 # What I would like: bin(1) -> 0b00000001 

有没有办法做到这一点?

使用format()函数 :

 >>> format(14, '#010b') '0b00001110' 

format()函数简单地格式化格式规范迷你语言后的input。 #使得格式包括0b前缀,并且010大小格式化输出以适应10个字符宽度,具有0填充; 0b前缀为2个字符,另外8个为二进制数字。

这是最紧凑和直接的select。

如果将结果放在较大的string中,请使用str.format() ,并将format()函数的第二个参数放在占位符冒号后面{:..}

 >>> 'The produced output, in binary, is: {:#010b}'.format(14) 'The produced output, in binary, is: 0b00001110' 

如果您不想使用0b前缀,只需放下#并调整字段的长度:

 >>> format(14, '08b') '00001110' 
 >>> '{:08b}'.format(1) '00000001' 

请参阅: 格式规范迷你语言


注意对于Python 2.6或更高版本,您不能在之前省略位置参数标识符,因此请使用

 >>> '{0:08b}'.format(1) '00000001' 

我在用

 bin(1)[2:].zfill(8) 

将打印

 '00000001' 

您可以使用string格式化迷你语言:

 def binary(num, pre='0b', length=8, spacer=0): return '{0}{{:{1}>{2}}}'.format(pre, spacer, length).format(bin(num)[2:]) 

演示:

 print binary(1) 

输出:

 '0b00000001' 

编辑: 基于@Martijn彼得斯的想法

 def binary(num, length=8): return format(num, '#0{}b'.format(length + 2)) 

你可以使用这样的东西

 ("{:0%db}"%length).format(num) 
 module Adder( input upperBit, lowerBit, c_in, output s, c_out) write gate1, gate2, gate3 xor (gate1, upperBit, lowerBit) xor (s, gate1, c_in) and (upperBit, lowerBit) and (gate1, c_in) or (c_out, gate1, gate2) endmodule module ful_adder8( input [7:0) a, b input c_in output [7:0) s, output c_out) write [7:0] carry full_adder fa0( a(a[o]) b(b[0]) c_in(c_in) s(s[0]) c_out(carry[0])) full_adder fa0( a(a[o]) b(b[0]) c_in(c_in) s(s[0]) c_out(carry[0])) full_adder fa0( a(a[o]) b(b[0]) c_in(c_in) s(s[0]) c_out(carry[0])) full_adder fa0( a(a[o]) b(b[0]) c_in(c_in) s(s[0]) c_out(carry[0])) full_adder fa0( a(a[o]) b(b[0]) c_in(c_in) s(s[0]) c_out(carry[0])) full_adder fa0( a(a[o]) b(b[0]) c_in(c_in) s(s[0]) c_out(carry[0])) full_adder fa0( a(a[o]) b(b[0]) c_in(c_in) s(s[0]) c_out(carry[0])) full_adder fa0( a(a[o]) b(b[0]) c_in(c_in) s(s[0]) c_out(carry[0])) endmodule test def split (n): return (n&0x1,n&0x2,n&0x4,n&0x8,n&0x10,n&0x20,n&0x40,n&0x80) def glue (b0,b1,b2,b3,b4,b5,b6,b7,c): t = 0 if b0: t += 1 if b1: t += 2 if b2: t += 4 if b3: t += 8 if b4: t += 16 if b5: t += 32 if b6: t += 64 if b7: t += 128 if c: t += 256 return t def myadd (a,b): (a0,a1,a2,a3,a4,a5,a6,a7) = split(a) (b0,b1,b2,b3,b4,b5,b6,b7) = split(b) (s0,s1,s2,s3,s4,s5,s6,s7,c) = addEightBits(a0,a1,a2,a3,a4,a5,a6,a7,b0,b1,b2,b3,b4,b5,b6,b7,false) return glue (s0,s1,s2,s3,s4,s5,s6,s7,c) 

您可以使用zfill:

 print str(1).zfill(2) print str(10).zfill(2) print str(100).zfill(2) 

打印:

 01 10 100 

我喜欢这个解决scheme,因为它不仅在输出数字的时候有帮助,而且当你需要把它分配给一个variables时…例如 – x = str(datetime.date.today()。month).zfill(2)返回x为'02'为feb的月份。

有时你只想要一个简单的一行:

 binary = ''.join(['{0:08b}'.format(ord(x)) for x in input]) 

Python 3