Eat.随 发表于 2023-12-7 11:49:01

求助

请问这一题的代码
10.2. Exercise
Dougie Dog has invented an "encryption" technique to keep secrets from the Ferocious Kittens. Fortunately, cats are extremely intelligent, and have cracked the simple code:
  1. Letters are grouped into pairs. Add a space to the end of the stringif necessary to give it an even number of characters (here "character" means char.
  2. Make an int from each pair by sticking the bits from the first letterin front of the bits from the second letter. You may assume that we are using 8-bit ASCII.
3. XOR the result with 31337.
Here's two examples of encryption:"cats" and "kittens".
1. Pairs:"ca ts"
"ki tt en s_"(_ represents a space)
2. into ints:25441 29811
27497 29812 25966 29472
3. XOR with 31337:6408 3610
4352 3613 7943 2377
Decryption is performed with the same steps, but in reverse order.
·The Ferocious Kittens have intercepted two secret messagesfrom Dougie Dog:
  15643 6913 6916 23040 2377 6985 6408 3657 56383084 2119 15910 23079 13629 23101 10300 1055723073 13092 23369
·Write a program that decrypts them.
  (hint: this will be a lot easier if you begin by writing a program toencrypt values -- you can check each step with"cats" and "kittens" to make sure you understand the process!)
  ·You must use a function to split a large integer into two separateletters. This function may not print anything to the screen. (hint: how can a function return two values?)

FishC_GPT 发表于 2023-12-7 11:49:47

这个问题看起来有些复杂,但是我们可以分步骤来解决。首先,我们需要写一个加密函数将字符串加密成数字。然后,我们再写一个解密函数将数字解密成字符串。下面是一个示例代码,你可以参考一下:

def encrypt(string):
    # 第一步:将字符串分组成对,并添加空格以获得偶数个字符
    if len(string) % 2 != 0:
      string += " "
   
    pairs = []
    for i in range(0, len(string), 2):
      pair = string + string
      pairs.append(pair)
   
    # 第二步:将每对字符转换为数字
    ints = []
    for pair in pairs:
      first = ord(pair) # 将第一个字符转换为ASCII码
      second = ord(pair) # 将第二个字符转换为ASCII码
      combined = (first << 8) + second # 将第一个字符的ASCII码位移到高位,再与第二个字符的ASCII码相加
      ints.append(combined)
   
    # 第三步:将结果与31337进行异或运算
    encrypted = []
    for num in ints:
      xor_result = num ^ 31337
      encrypted.append(xor_result)
   
    return encrypted


def decrypt(nums):
    decrypted = []
    for num in nums:
      xor_result = num ^ 31337
      decrypted.append(xor_result)
   
    pairs = []
    for num in decrypted:
      first = num >> 8 # 将整数右移8位,获得第一个字符的ASCII码
      second = num & 255 # 通过与255进行与运算,获得第二个字符的ASCII码
      pair = chr(first) + chr(second) # 将两个ASCII码转换为字符
      pairs.append(pair)
   
    string = "".join(pairs)
    return string


# 测试加密函数
encrypted = encrypt("cats")
print(encrypted)# 输出:

# 测试解密函数
decrypted = decrypt()
print(decrypted)# 输出:"cats"

现在你可以将这些函数用于解密题目中给出的密文。希望对你有所帮助!

以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。
页: [1]
查看完整版本: 求助