Skip to content

Instantly share code, notes, and snippets.

@BbsonLin
Last active January 3, 2019 14:22
Show Gist options
  • Save BbsonLin/cd33f39c7c498e172c8ec2e9a9c974f0 to your computer and use it in GitHub Desktop.
Save BbsonLin/cd33f39c7c498e172c8ec2e9a9c974f0 to your computer and use it in GitHub Desktop.
import serial
FLAG = 0x7E
HEX_NUMBER = 0xFF
HEX_NUMBERS = [0xFF, 0x15]
# INT <---> STRING(hex)
print(FLAG, type(FLAG)) # 126 <class 'int'>
print(hex(FLAG), type(hex(FLAG))) # 0x7e <class 'str'>
print(int(hex(FLAG), 16)) # 126
# Addition two hex number
print(FLAG+HEX_NUMBER) # 381
# Sum hex number list
print(sum(HEX_NUMBERS)) # 276
# Get sum hex string and get last byte
hex_sum = hex(sum(HEX_NUMBERS))
print(hex_sum, type(hex_sum)) # 0x114 <class 'str'>
print(hex_sum[:2] + hex_sum[-2:]) # 0x14
# Use serial.to_bytes function transfer hex sequence into byte string
b_string = serial.to_bytes(HEX_NUMBERS)
print(b_string, type(b_string)) # b'\xff\x15' <class 'bytes'>
# Convert byte string to hex string
print(b_string.hex(), type(b_string.hex())) # ff15 <class 'str'>
# ASCII string to hex number
# Ref: https://stackoverflow.com/questions/8088375/how-do-i-convert-a-single-character-into-its-hex-ascii-value-in-python
print(hex(ord("c"))) # '0x63'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment