Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert number to binary string

Tags:

python

hex

binary

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

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

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

Clarification:

I am going from int to hex.

Also, I need it to be escaped.

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

Also, it needs to be able to take any Python integer. IE. something larger than an Int.

Edit:

Here is the best solution so far I have cobbled together from Paolo and Devin's post.

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

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

    return num.decode('hex')
like image 735
Unknown Avatar asked Dec 13 '22 05:12

Unknown


1 Answers

You can use string formatting:

>>> number = 123456789
>>> hex = "%X" % number
>>> hex
'75BCD15'
like image 188
Paolo Bergantino Avatar answered Dec 24 '22 04:12

Paolo Bergantino