【问题标题】:How do I actually decode a string to hex? [duplicate]我如何实际将字符串解码为十六进制? [复制]
【发布时间】:2021-06-07 01:07:40
【问题描述】:

我需要解决一些小练习,我需要对一些字符串进行异或运算。 我发现了这个超级简单的代码,它简单地编码和解码:

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 属性,那么就没有 decode 属性。

但是那我该怎么办呢?我实际上只是想在类型之间进行转换。 (从字符串到字节,再到base64)

【问题讨论】:

  • 试试,int(hex_str, base=16)
  • 使用binascii.unhexlify()

标签: python


【解决方案1】:
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"

【讨论】:

    【解决方案2】:

    代码

    a = 102
    
    print(hex(a))
    

    输出:

    0x66
    

    我们还可以使用带有 float() 函数的 hex() 函数将浮点值转换为十六进制。以下代码实现了这一点。

    a = 102.18
    
    print(float.hex(a))
    

    输出:

    0x1.98b851eb851ecp+6
    

    我们无法使用此函数转换字符串。所以如果我们有一个十六进制字符串,想把它转换成十六进制数的情况,我们是不能直接做的。对于这种情况,我们必须使用 int() 函数将此字符串转换为所需的十进制值,然后使用 hex() 函数将其转换为十六进制数。

    【讨论】:

    • 酷!但是,这以整数值开头,因此不代表我遇到的问题
    猜你喜欢
    • 2012-05-30
    • 2011-04-01
    • 2020-11-11
    • 2018-06-16
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    相关资源
    最近更新 更多