Search code examples
pythonstringhexbytedecode

Decoding python data


Sorry for what might be a quite simple question. I know a few languages, but I'm new regarding python. I'm collecting via an IOT device the following data and here are all the info I can get :

print('This is my data : %s' % (data)) => "This is my data : b'\x95\xfe683475065015121'"
print(type(data)) => "<class 'str'>"

The thing is, I'd like to get numeric values extracted from data such as :

  • Discard the \x95\xfe at the begining
  • a = 68.3 (3 first digits / 10)
  • b = 475 or 475.0 (3 next digits)
  • c = 065 or 65.0 (3 next digits)...
  • ... (I'll get the rest from here I think.)

Thanks a lot for your help and have a great day.

PS : I already tried float.fromhex(data[y:Z]) - or data.decode("hex"), but no luck... bytes.fromhex(data[y:z]) got me a strange result as well...


Solution

  • Sure:

    t = b'\x95\xfe683475065015121'
    t = t[2:]  # disregard \x95\xfe
    print(t)
    
    a = int(t[:3]) / 10
    b = int(t[3:6])
    c = int(t[6:9])
    print(a, b, c)  # >>> 68.3 475 65