Skip to content

Instantly share code, notes, and snippets.

@devlights
Last active December 7, 2018 07:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save devlights/ff14ad78ec2a2ace8b13304976c5c355 to your computer and use it in GitHub Desktop.
Save devlights/ff14ad78ec2a2ace8b13304976c5c355 to your computer and use it in GitHub Desktop.
Pythonで 数値 -> バイナリ -> 16進文字列 -> バイナリ -> 数値への変換。
In[28]: # 数値からバイナリへ
In[29]: a_number = 1024
In[30]: a_number.to_bytes(4, byteorder='big')
Out[30]: 
b'\x00\x00\x04\x00'
In[31]: # バイナリから16進文字列へ
In[32]: _.hex()
Out[32]: 
'00000400'
In[33]: # 16進文字列からバイナリへ
In[34]: binascii.unhexlify(_)
Out[34]: 
b'\x00\x00\x04\x00'
In[35]: # バイナリから数値へ
In[36]: int.from_bytes(_, byteorder='big')
Out[36]: 
1024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment