Is there a way to encode/decode hex like from Python 2?

99 views Asked by At

Summary: I'm creating a project using the Wii Balance Board and Python. I found a module to use in GitHub. It is unfortunately written in Python 2. I fixed the code using 2to3, except I couldn't find a workaround for functions like x.decode('hex') or x.encode('hex')

The inputs from the board is some stuff like \xa1 \x00\x00\x02\x00\x00\xbe (example) and I think I'll have to convert these to strings in order for that to work.

I tried binascii.b2a(), codecs.getdecoder() and bytes.fromhex()

Expectations and what happened:* Expected result is taking a string of hex bytes (\xa1 \x00\x00\x02\x00\x00\xbe for example) and then using them in the given code:

INPUT_STATUS = 20
INPUT_READ_DATA = 21
EXTENSION_8BYTES = 32
#(...)
data = self.receivesocket.recv(25)
intype = int(data.encode("hex")[2:4])
if intype == INPUT_STATUS:
  self.setReportingType()
elif intype == INPUT_READ_DATA:
  if self.calibrationRequested:
  packetLength = (int(str(data[4]).encode("hex"), 16) / 16 + 1)
  self.parseCalibrationResponse(data[7:(7 + packetLength)])

  if packetLength < 16:
    self.calibrationRequested = False
    elif intype == EXTENSION_8BYTES:
    self.processor.mass(self.createBoardEvent(data[2:12]))
  else:
    print("ACK to data write received")

Result I get is:

#using fromhex:
  File "wiboard2.py", line 37, in decode
    val = bytes.fromhex(str(n))
ValueError: non-hexadecimal number found in fromhex() arg at position 1

#using binascii:
  File "wiboard2.py", line 38, in decode
    return binascii.b2a_hex(n[1:].replace(" ", "").replace("\\", "").replace("x", ""))
TypeError: a bytes-like object is required, not 'str'

#this may not help, i've done some editing that won't make it work; but it gives the same error without the "replace"s

Any help is appreciated. If I was unclear anywhere, please tell me.

0

There are 0 answers