0

I need tos solve some small exercises, where I need to do some xor'ing on some strings. I found this super simple code, which simply encodes, and decodes:

hex_str = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
decoded = hex_str.decode("hex")
# I'm killing your brain like a poisonous mushroom
base64_str = decoded.encode("base64")
# SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t

This fails with:

AttributeError: 'str' object has no attribute 'decode'

Which I guess makes sense, if there no decode attribute, then there is no decode attribute.

But what do I do then? I literally just want to convert between types. (from string to bytes, to base64)

2 Answers2

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"
enzo
  • 9,861
  • 3
  • 15
  • 38
-1

Code

a = 102

print(hex(a))

Output:

0x66

We can also convert float values to hexadecimal using the hex() function with the float() function. The following code implements this.

a = 102.18

print(float.hex(a))

Output:

0x1.98b851eb851ecp+6

We cannot convert a string using this function. So if we have a situation where we have a hexadecimal string and want to convert it into the hexadecimal number, we cannot do it directly. For such cases, we have to convert this string to the required decimal value using the int() function and then convert it to the hexadecimal number using the hex() function.