def TTB(): a = bytearray (text1, "cp1251") b = list(map(int, a)) c = list(map(str, a)) for i in range (len(c)): if (int(len(c)) < 8): c[i] = "0" + str(c[i]) f = ' '.join (c) int_in = int(f, 16) bin_out = bin(int_in)[:2].zfill(len(f.strip())*2) converted = str(bin_out) text1 = input("your text:") c = TTB() print(c) 

For example, symbol 1 would be 49 and 1001001, and I need 01001001. And more! These are 33 and 110011 and you need 00110011. How to get each character from ASCII to 8 digit 0-255

  • Calculate the length of the resulting string and add zeros to the beginning to 8. - Vladimir Martyanov
  • The second option is to do the conversion on the low / high bit check. And if you enter 8 shifts, the leading zeros will be obtained. - Vladimir Martyanov
  • one
    In fact, zfill is the same, and you use it, just in another place. If you need to finish the line s = '1001001' to 8 digits, make s.zfill(8) for it. - insolor
  • zfill (8) is obtained only for the 1st character. If the character repeats, then 0 is lost. For example 111 -> 049049049 in dv. si 1001001000001001001000001001001 is only 31, but it should be 32 - user270218

2 answers 2

For example:

 def str2bin(text): bin_words = [bin(c)[2:].rjust(8, '0') for c in text.encode('cp1251')] return ' '.join(bin_words) text = "Hello" print(str2bin(text)) text = "Привет" print(str2bin(text)) 

Console:

 01001000 01100101 01101100 01101100 01101111 11001111 11110000 11101000 11100010 11100101 11110010 
  • I get a syntax error on join - user270218
  • @ user270218, now I will look into your thoughts and understand how you copied my code and what the error is there :) UPD. I think that with copy-paste, your indentations broke down there :) - gil9red
  • The point is that I enter the source data for example: 12ravl!?: '*. The output will be each character has its own digit in ASCII (1 = 49, I = 255) here I take 49 = 01001001, I = 11111111 - user270218
  • And on the console it turns out 1001001 7 characters (! = 33) 110011, but I need 00110011 if it repeats 3 times, then 32 characters should turn out - user270218
  • @ user270218,7 characters could not work with my code due to .rjust(8, '0') . print(str2bin("12ратаьвл!?:'*")) -> 00110001 00110010 11110000 11100000 11110010 11100000 11111100 11100010 11101011 00100001 00111111 00111010 00100111 00101010 - gil9red

Works in Python 2.7 and higher:

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