I tried to encrypt p101-103 of the second volume with Python. All encrypt HELLO.
Input
HELLO
s=input()
n=len(s)
l=[]
for i in range(n):
l.append(str(bin(ord(s[i])))[2:])
m="".join(l)
odd=m[::2]
even=m[1::2]
num=len(even)
for j in range(num):
print(even[j],end="")
print(odd[j],end="")
print(odd[-1])
Output
01100010001010011001100011000110111
First convert to ASCII. This is OK with ord (). Unicode and ASCII have the same alphabet. Yeah.
Binary numbers are difficult to handle, so If you use str () to make a character string, you can retrieve the numbers in each digit. With str (bin (ord (s [i]))) [2:], take the leading 0b.
I wondered how to exchange the first number for the second number, I tried to process it that seems to be the A problem of AtCoder.
It is divided into odd-numbered and even-numbered and output alternately.
Since odd has one more character, only odd [-1] is output at the end. If the input is an even number of alphabets, I have to change it again, For the time being, this time.
Now, on the contrary, try returning 01100010001010011001100011000110111 to HELLO.
Input
01100010001010011001100011000110111
s=input()
even=s[:-2:2]
odd=s[1::2]
l=[]
n=len(even)
for i in range(n):
l.append(odd[i])
l.append(even[i])
l.append(s[-1])
m="".join(l)
num=len(l)//7
for j in range(num):
print(chr(int(m[7*j:7*(j+1)],2)),end="")
It's basically the opposite of encryption, so it was still easy.
I knew that int ('number in binary notation', 2) was enough to convert a binary number back to a decimal number, so I could write it simply. Convert binary, octal, and hexadecimal numbers and strings to each other with Python
First, convert the DAVID to ASCII code. 10001001000001101011010010011000100 This is the key.
The rules of encryption are -If the plaintext and key elements are the same, the ciphertext will be 0. -If the plaintext and key elements are different, the ciphertext will be 1. It's an exclusive OR (XOR).
Input
HELLO
DAVID
s=input()
key=input()
n=len(s)
#ASCII conversion
l_s=[]
l_k=[]
for i in range(n):
l_s.append(str(bin(ord(s[i])))[2:])
l_k.append(str(bin(ord(key[i])))[2:])
a_s="".join(l_s)
a_k="".join(l_k)
num=len(a_s)
cipher=[]
for j in range(num):
if a_s[j]==a_k[j]:
cipher.append("0")
else:
cipher.append("1")
print(*cipher,sep="")
Output
00011000000100001101000001010001011
Now, conversely, move 00011000000100001101000001010001011 back to HELLO using the key DAVID. If the ciphertext and key elements are the same, the plaintext will be 0, and if they are different, it will be 1. It's the same as when encrypting.
Input
00011000000100001101000001010001011
DAVID
s=input()
key=input()
n=len(key)
#ASCII converter key
l_k=[]
for i in range(n):
l_k.append(str(bin(ord(key[i])))[2:])
k="".join(l_k)
num=len(s)
l_p=[]
for j in range(num):
if s[j]==k[j]:
l_p.append("0")
else:
l_p.append("1")
p="".join(l_p)
n_p=len(p)//7
for l in range(n_p):
print(chr(int(p[7*l:7*(l+1)],2)),end="")
Output
HELLO
Recommended Posts