オランのまったりな
開発日記
Converting to and from string/hex/bytes type in python
Bantukul Olarn
    
Nov 29 2017 21:00
  

Hex/String/Bytes conversion templates.

Python 3:

#encoding: utf8

unicode_str = "sample text"
bytes_data = unicode_str.encode()
hex_data = bytes_data.hex()

bin_from_unicode = unicode_str.encode()
bin_from_hexstr = bytes.fromhex(hex_data)

str_from_bytes = bytes_data.decode()
bytes_from_hexstr = bytes.fromhex(hex_data).decode()

hexstr_from_unicode = unicode_str.encode().hex()
hexstr_from_bin = bytes_data.hex()

Python 2

# -*- coding: utf-8 -*-
import binascii

# since plain str = bytes in python2, it will be called plain_byte_str here
plain_byte_str = "sample text"
unicode_str = unicode(plain_byte_str)
hex_data = binascii.b2a_hex(plain_byte_str)

plain_byte_str_from_unicode = unicode_str.encode()
plain_byte_str_from_hexstr = binascii.unhexlify(hex_data)

bytes_from_hexstr = binascii.unhexlify(hex_data)

unicode_from_hexstr = unicode(binascii.unhexlify(hex_data))
hexstr_from_unicode = binascii.b2a_hex(unicode_str.encode())

Tags: