Hex() method of bytes class in Python

Overview:

  • The hex() instance method of bytes class, converts a bytes object into a string of hexadecimal digits.
  • The string returned by hex() method will have two hexadecimal digits for each byte from the bytes object.

Note: An escape character \x inside a byte literal means the ASCII character is encoded as hexadecimal digits.

Example:

# Example python program using hex() to convert a bytes literal

# of ascii characters to a string literal of hexadecimal digits

bytesLiteral = b"hell\x6f";

hexVal       = bytesLiteral.hex();

print("Bytes literal of ascii characters:");

print(bytesLiteral);

 

print("String literal of hexadecimal digits:");

print(hexVal);

 

bytesLiteral = b"\x77\x6f\x72\x6c\x64";

hexVal       = bytesLiteral.hex();

print("Bytes literal of ascii characters:");

print(bytesLiteral);

 

print("Bytes literal of hexadecimal digits converted into a string literal:");

print(hexVal);

 

Output:

Bytes literal of ascii characters:

b'hello'

String literal of hexadecimal digits:

68656c6c6f

Bytes literal of ascii characters:

b'world'

Bytes literal of hexadecimal digits converted into a string literal:

776f726c64

 


Copyright 2024 © pythontic.com