I am making on RSA. I need to put zeros on the left side of my really big binary number. I have this list:
text = ['110000100001101000000011011110000110101000001100100000011000010000010000000001101101', '11101000000111010100001100001000011011000000110111000001100101']
And I want to get this
text= ['0000110000100001101000000011011110000110101000001100100000011000010000010000000001101101', '000011101000000111010100001100001000011011000000110111000001100101']
In this case there miss 4 zeros on the left side. I tried this loop:
i = 0;
while i < len(text):
j = 0
zeroCount = (10 - (len(text[i]) % 11)) + 1
while j < zeroCount:
text[i] = '0' + text[i]
j += 1
i += 1
Which doesn't work in my PyQt project. However it works when I have tried it in blank untitled1.py "sketchbook". It's kind of confusing. What am I doing wrong and why it works in my "sketchbook"?
Try something like this:
for i, binary_number in enumerate(text):
text[i] = ((10 - (len(text[i]) % 11)) + 1) * '0' + text[i]
this will add the zeros you want to every binary string in your list.
Use list comprehension:
text = ['110000100001101000000011011110000110101000001100100000011000010000010000000001101101', '11101000000111010100001100001000011011000000110111000001100101']
result = ["0"*(10 - (len(i) % 11) + 1) + "{}".format(i) for i in text]
It will add 4 zeros in front of each binary string.
print(result)
['0000110000100001101000000011011110000110101000001100100000011000010000010000000001101101', '000011101000000111010100001100001000011011000000110111000001100101']
I think this is the most straightforward (and up to date) way of doing it.
bin_strs = ['110000100001101000000011011110000110101000001100100000011000010000010000000001101101',
'11101000000111010100001100001000011011000000110111000001100101']
bin_strs_pad = ['0' * ((10 - (len(curr) % 11)) + 1) + curr for curr in bin_strs]
You can use format
to get the desired result. Use the format specifier 0xxb
, where xx is the desired number of bits in the output. For example, if you want the numbers to be 16 bits long:
>>> t = "11001" # example, non zero-padded binary number
>>>"{0:016b}".format(int(t, 2)) # pad with zeros up to 16 bits
'0000000000011001'
Alternatively, with f-strings (Python 3.6+):
>>> t = "11001"
>>> f"{int(t,2):016b}"
'0000000000011001'
The other answers are fixated on having the shortest list comprehension, and matching OP's modulo 11 approach, but this is the one obvious way to format a binary number to a desired length.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.