Converting a number to a binary string

Is this the best way to convert a Python number to a hexadecimal string?

number = 123456789
hex(number)[2:-1].decode('hex')

Sometimes it doesn't work and complains about an odd-length string when you do 1234567890.

Clarification:

I am switching from int to hex.

In addition, I need it to be shielded.

IE: 1234567890 → '\ x49 \ x96 \ x02 \ xd2' not '499602D2'

In addition, it should be able to accept any Python integer. IE something more than int.

Edit:

Here is the best solution that I still remember from Paolo and Devin's post.

def hexify(num):
    num = "%x" % num

    if len(num) % 2:
        num = '0'+num

    return num.decode('hex')
+3
source share
7 answers

You can use string formatting :

>>> number = 123456789
>>> hex = "%X" % number
>>> hex
'75BCD15'
+6

, , struct ?

>>> hex(123456789)
'0x75bcd15'

:

>>> struct.pack('i', 123456789)
'\x15\xcd[\x07'

, '\x5b' == '['.

, :

>>> struct.pack('>i', 123456789)
'\x07[\xcd\x15'

: , ", ", AFAIK longs python ( ). , . :

>>> n = 123456789012345678901234567890

:

>>> hex(n)
'0x18ee90ff6c373e0ee4e3f0ad2L'

:

>>> s = ''
>>> while n >= 2**32:
...  n, r = divmod(n, 2**32)
...  s = struct.pack('>l', r) + s
... 
>>> s = struct.pack('>l', n) + s

, s hex(n) :

>>> s
'\x00\x00\x00\x01\x8e\xe9\x0f\xf6\xc3s\xe0\xeeN?\n\xd2'
+5

, 1234567890.

. "AAB" , 2 4 ? . , . , 0AAB AAB0? , , , .

. (('0' + foo) if len(foo) % 2 else foo).decode('hex') foo - , %x.

+1
+1

, - . , :

>>> hex = lambda n: '%X' % n
>>> hex(42)
'2A'
>>> hex = lambda n: '%x' % n
>>> hex(42)
'2a'
>>> def escaped(n):
...     s = hex(n)
...     if len(s) & 1:
...          s = '0' + s
...     return ''.join(chr(int(s[i:i + 2], 16)) for i in range(0, len(s), 2))
...
>>> escaped(123)
'{'
>>> escaped(1234)
'\x04\xd2'
>>> escaped(12348767655764764654764445473245874398787989879879873)
'!\x01^\xa4\xdf\xdd(l\x9c\x00\\\xfa*\xf3\xb4\xc4\x94\x98\xa9\x03x\xc1'

, escaped . .

0

, , . , , :

>>> "{0:08x}".format(123456789).decode("hex")
'\x07[\xcd\x15'
>>> "{0:08x}".format(1234567890).decode("hex")
'I\x96\x02\xd2'

, "" . , :

>>> "{0:012x}".format(123456789).decode("hex")
'\x00\x00\x07[\xcd\x15'
>>> "{0:012x}".format(1234567890).decode("hex")
'\x00\x00I\x96\x02\xd2'

Edit:

"" , math.log:

>>> def int2str(n):
        l = int(math.ceil(math.log(n, 256) / 2) * 4)
        return ("{0:0{1}x}").format(n, l).decode("hex")

>>> int2str(123456789)
'\x07[\xcd\x15'
>>> int2str(1234567890)
'I\x96\x02\xd2'
0

, , - "array" :

from array import array
binArr = array('B')

while(data):
    d = data & 0xFF
    binArr.append(d)
    data >>= 8

hexStr = binArr.tostring()
0

Source: https://habr.com/ru/post/1705607/


All Articles