Sazzy
Sazzy

Reputation: 1994

python: string of hex values to binary

This is a sample of my input:

a = 41cf4a077a7454

They represent hex values, x41 xCF x4A etc...

I require to convert them into one string of binary like this (DESIRED OUTPUT):

01000001110011110100101000000111011110100111010001010100

x41 = 01000001 xCF = 11001111 x4A = 01001010 etc...

The code I used to do it looked like this:

return bin(int(str(a), 16))[2:]

However, it produces a string without a zero at the front:

1000001110011110100101000000111011110100111010001010100

It appears the zero gets chopped as it's interpreted as an integer. Is there a way I can keep the zero, because not every string being converted begins with a zero in binary.

I hope this makes sense. Thank you.

Upvotes: 1

Views: 4162

Answers (2)

user2725093
user2725093

Reputation: 221

One line solution:

>>> a = '41cf4a077a7454'
>>> ''.join('{0:08b}'.format(int(x, 16)) for x in (a[i:i+2] for i in xrange(0, len(a), 2)))
'01000001110011110100101000000111011110100111010001010100'

Or extension for your solution:

>>> a = '41cf4a077a7454'
>>> x = bin(int(str(a), 16))[2:]
>>> '0'*(8-len(x)%8) + x
'01000001110011110100101000000111011110100111010001010100'

Upvotes: 2

jabaldonedo
jabaldonedo

Reputation: 26582

This solution could work for you.

>>> a = '41cf4a077a7454'
>>> b = [a[2*i]+a[2*i+1] for i in range(len(a)/2)]
 ['41', 'cf', '4a', '07', '7a', '74', '54']
>>> c = map(lambda x: "{0:08b}".format(int(x, 16)), b)
['01000001',
 '11001111',
 '01001010',
 '00000111',
 '01111010',
 '01110100',
 '01010100']
>>> "".join(c)
'01000001000111001100111111110100010010101010000000000111'

Upvotes: 1

Related Questions