1、字符串转bytes

  1. '''
  2. string to bytes
  3. eg:
  4. '0123456789ABCDEF0123456789ABCDEF'
  5. b'0123456789ABCDEF0123456789ABCDEF'
  6. '''
  7. def stringTobytes(str):
  8. return bytes(str,encoding='utf8')


2、bytes转字符串

  1. '''
  2. bytes to string
  3. eg:
  4. b'0123456789ABCDEF0123456789ABCDEF'
  5. '0123456789ABCDEF0123456789ABCDEF'
  6. '''
  7. def bytesToString(bs):
  8. return bytes.decode(bs,encoding='utf8')


3、十六进制字符串转bytes

  1. '''
  2. hex string to bytes
  3. eg:
  4. '01 23 45 67 89 AB CD EF 01 23 45 67 89 AB CD EF'
  5. b'\x01#Eg\x89\xab\xcd\xef\x01#Eg\x89\xab\xcd\xef'
  6. '''
  7. def hexStringTobytes(str):
  8. str = str.replace(" ", "")
  9. return bytes.fromhex(str)
  10. # return a2b_hex(str)


4、bytes转十六进制字符串

  1. '''
  2. bytes to hex string
  3. eg:
  4. b'\x01#Eg\x89\xab\xcd\xef\x01#Eg\x89\xab\xcd\xef'
  5. '01 23 45 67 89 AB CD EF 01 23 45 67 89 AB CD EF'
  6. '''
  7. def bytesToHexString(bs):
  8. # hex_str = ''
  9. # for item in bs:
  10. # hex_str += str(hex(item))[2:].zfill(2).upper() + " "
  11. # return hex_str
  12. return ''.join(['%02X ' % b for b in bs])
09-20 20:56