1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

記事投稿キャンペーン 「2024年!初アウトプットをしよう」

Python小ネタASCII⇔HEX文字列変換

Last updated at Posted at 2024-01-14

はじめに

ASCII文字列とHEX文字列を相互に変換する方法をまとめる。

ord()とchr()で変換する

ASCII文字列→HEX文字列はord()、HEX文字列→ASCII文字列はchr()で変換できる。

ascii_hex.py
import re 

ascii_string = 'abcdefghi-ABCDEFGHI_0123456789'

#====================
# ASCII→HEX
#====================
# ASCII文字列を1文字ずつ分割してリスト化
ascii_list = list(ascii_string)

# 内包表記で ASCII文字のリストを ord() で整数にして f-stringでHEX文字に変換
hex_list=[f'{ord(i):02X}' for i in ascii_list]

# 変換したHEX文字を結合
hex_string=''.join(hex_list)
print(f'# {hex_string=}')
# hex_string='6162636465666768692D4142434445464748495F30313233343536373839'


#====================
# HEX→ASCII
#====================
# HEX文字列を2文字ずつ分割してリスト化
hex_list = re.split('(..)',hex_string)[1::2]

# 内包表記で HEX文字のリストを int() で整数にして chr() でASCII文字に変換
ascii_list=[chr(int(i,16)) for i in hex_list]

# 変換したASCII文字を結合
ascii_string=''.join(ascii_list)
print(f'# {ascii_string=}')
# ascii_string='abcdefghi-ABCDEFGHI_0123456789'

HEX⇔ASCII それぞれ1行で表現すると

ascii_hex.py
import re 

ascii_string = 'abcdefghi-ABCDEFGHI_0123456789'

# ASCII→HEX
hex_string = ''.join([f'{ord(i):02X}' for i in list(ascii_string)])
print(f'# {hex_string=}')
# hex_string='6162636465666768692D4142434445464748495F30313233343536373839'

# HEX→ASCII
ascii_string= ''.join([chr(int(i,16)) for i in re.split('(..)',hex_string)[1::2]])
print(f'# {ascii_string=}')
# ascii_string='abcdefghi-ABCDEFGHI_0123456789'

以上

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?