Sam Roberts
Sam Roberts

Reputation: 399

How can I get 0x1b87 to print like \x1b\x87 in Python?

How can I get 0x1b87 to print like \x1b\x87 in Python?

$ python
Python 2.7.9 (default, Apr  2 2015, 15:33:21) 
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> hex(0x0d90 ^ 0x1617)
'0x1b87'

Upvotes: 2

Views: 168

Answers (2)

vaultah
vaultah

Reputation: 46563

I'm going to use format(..., 'x') for hexadecimal representation, avoiding the unnecessary slicing (hex(...)[2:]).

Python 2

Just decode the string (using the hex codec):

>>> format(0x0d90 ^ 0x1617, 'x').decode('hex')
'\x1b\x87'

or pack the integer with struct.pack (> for big-endian order, H for unsigned short - change format character to meet your requirements)

>>> import struct
>>> struct.pack('>H', 0x0d90 ^ 0x1617)
'\x1b\x87'

Python 3

bytes.fromhex does that:

In [1]: bytes.fromhex(format(0x0d90 ^ 0x1617, 'x'))
Out[1]: b'\x1b\x87'

struct.pack is still an option, format strings are as for Python 2 (see the previous section):

In [2]: import struct

In [3]: struct.pack('>H', 0x0d90 ^ 0x1617)
Out[3]: b'\x1b\x87'

The hex codec is now one of the binary transforms, use codecs.decode:

In [4]: import codecs

In [5]: codecs.decode(format(0x0d90 ^ 0x1617, 'x'), 'hex')
Out[5]: b'\x1b\x87'

Python 3.2 and newer

Python 3.2 introduced the cool int.to_bytes method:

In [4]: (0x0d90 ^ 0x1617).to_bytes(4, 'big')
Out[4]: b'\x00\x00\x1b\x87'

It will produce a fixed number of bytes (4 in this example) or the OverflowError "if the integer is not representable with the given number of bytes".

There's a way to calculate the minimum number of bytes necessary to represent the integer:

In [22]: i = 0x0d90 ^ 0x1617

In [23]: i.to_bytes((i.bit_length() // 8) + 1, 'big')
Out[23]: b'\x1b\x87'

Also, consider specifying the signed argument that

determines whether two's complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

Upvotes: 6

dsgdfg
dsgdfg

Reputation: 1520

import struct
struct.pack(">H" ,int('0x1b87',16))

'\x1b\x87'
>>>

Upvotes: 2

Related Questions