我需要解决一些小的练习,在那里我需要做一些字符串的xor‘’ing。我找到了这个超级简单的代码,它只是简单地编码和解码:
hex_str = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
decoded = hex_str.decode("hex")
# I'm killing your brain like a poisonous mushroom
base64_str = decoded.encode("base64")
# SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t但以下几个方面都失败了:
AttributeError: 'str' object has no attribute 'decode'如果没有decode属性,那么就没有解码属性。
那我该怎么办呢?我只是想在类型之间进行转换。(从字符串到字节,到base64)
发布于 2021-06-06 17:07:40
import base64
hex_str = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
# Convert the hex string to bytes using the bytes' constructor
decoded = bytes.fromhex(hex_str)
assert decoded == b"I'm killing your brain like a poisonous mushroom"
# Convert the decoded bytes to base64 bytes using the base64 module
base64_bytes = base64.b64encode(decoded)
assert base64_bytes == b"SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"
# Convert the base64 bytes to string using bytes method decode
base64_str = base64_bytes.decode('ascii')
assert base64_str == "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"发布于 2021-06-06 17:03:53
码
a = 102
print(hex(a))输出:
0x66我们还可以使用带float()函数的十六进制函数将浮点数转换为十六进制。下面的代码实现了这一点。
a = 102.18
print(float.hex(a))输出:
0x1.98b851eb851ecp+6我们不能使用此函数转换字符串。因此,如果我们有一个十六进制字符串,并希望将它转换为十六进制数,我们就不能直接这样做。对于这种情况,我们必须使用int()函数将该字符串转换为必需的十进制值,然后使用十六进制()函数将其转换为十六进制数。
https://stackoverflow.com/questions/67861639
复制相似问题