Kevin
Kevin

Reputation: 3431

python 3 hex conversion

I'm trying to convert some code from 2 to 3. I have

val = str(''.join(map(chr, list(range(0, 256, 8)))))

and I need to translate

x = str(val).encode('hex')

and

x.decode('hex')

Thanks

Upvotes: 0

Views: 1380

Answers (2)

jfs
jfs

Reputation: 414189

Your Python 2 code:

val = str(''.join(map(chr, list(range(0, 256, 8)))))
x = str(val).encode('hex')
x.decode('hex')

Let's make version that works on both Python 2 and 3:

import binascii

val = bytearray(range(0, 0x100, 8))
x = binascii.hexlify(val)
binascii.unhexlify(x)

Upvotes: 0

John1024
John1024

Reputation: 113834

In python2, your code produces:

In [4]: val = str(''.join(map(chr, list(range(0, 256, 8))))) ;  val
Out[4]: '\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'
In [5]: x = str(val).encode('hex') ; x
Out[5]: '0008101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f0f8'
In [6]: x.decode('hex')
Out[6]: '\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'

To get the similar output in python3:

In [19]: import codecs
In [20]: val = ''.join(map(chr, range(0, 256, 8))) ; val
Out[20]: '\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0¨°¸ÀÈÐØàèðø'
In [21]: x = codecs.encode(val.encode('latin-1'), 'hex_codec') ; x
Out[21]: b'0008101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f0f8'
In [22]: codecs.decode(x, 'hex_codec')
Out[22]: b'\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'

Notes:

  1. The python3 version of x above is a byte-string. Since it is entirely ASCII, it can be converted to unicode simply via x.decode().

  2. The display of val toward the end of the string in the python3 code above does not match the python2 version. For a method of creating val which does match, see the next section.

Alternatives

Use bytes to create the string. Use binascii.hexlify to convert it to hex:

In [15]: val = bytes(range(0, 256, 8))
In [16]: val
Out[16]: b'\x00\x08\x10\x18 (08@HPX`hpx\x80\x88\x90\x98\xa0\xa8\xb0\xb8\xc0\xc8\xd0\xd8\xe0\xe8\xf0\xf8'
In [17]: binascii.hexlify(val)
Out[17]: b'0008101820283038404850586068707880889098a0a8b0b8c0c8d0d8e0e8f0f8'


More on unicode and character 0xf8

You wanted ø to be 0xf8. Here is how to make that work:

>>> s = chr( int('f8', 16) )
>>> s
'ø'

And, to convert s back to a hex number:

>>> hex(ord(s))
'0xf8'

Note that 0xf8' is the unicode code point of 'ø' and that that is not the same as the byte string representing the unicode character 'ø' which is:

>>> s.encode('utf8')
b'\xc3\xb8'

So, 'ø' is the 248th (0xf8) character in the unicode set and its byte-string representation is b'\xc3\xb8'.

Upvotes: 1

Related Questions