python - Joining bytes to create ctypes.c_char_p string -


i trying upgrade code written in python2, works in python3 , still works in python2. code snippet in question works under python2:

import ctypes import struct  class ethernet(ctypes.structure):      _fields_ = [('dst', ctypes.c_char_p)]      def __init__(self, packet):         (dst, ) = struct.unpack('!6s', packet[:6])          self.dst = ':'.join(['%02x' % (ord(octet), ) octet in dst])  def main():      p = b'\xab\xad\xba\xbe\x0f\xe9'     e = ethernet(p)      if b"ab:ad:ba:be:0f:e9" == e.dst:         print(true)     else:         print(false)  if __name__ == '__main__':     main() 

my problems start when move python3 warning same code:

file "test2.py", line 11, in <listcomp>   self.dst = ':'.join(['%02x' % (ord(octet), ) octet in dst])    typeerror: ord() expected string of length 1, int found 

so code doesn't work in python3.

the way can seem work :

    try: # python 3         self.dst = b':'.join([struct.pack('bb', ord('{:x}'.format((octet >> 4) & 0xf)), ord('{:x}'.format((octet >> 0) & 0xf))) octet in dst])     except typeerror: # python 2         self.dst = ':'.join(['%02x' % (ord(octet), ) octet in dst]) 

which messy, every way try it fields definition of ctypes.c_char_p blocks simple.

is there better way single line works in both python2 , python3 (no exceptions needed)

i don't know why can't mark correct answer such eryksun response worked me:

2.6+ has bytearray type, iterates integers. has b'' literals. formatting part in python 3 can use string , encode it, harmless in python 2. example:

dst = bytearray(packet[:6]);  self.dst = b':'.join([('%02x' % o).encode('ascii') o in dst])`  

eryksun jul 16 @ 15:39


Comments