views:

2299

answers:

8

I have ABC123EFFF, I want to have 01010101010001010101.

How?

+2  A: 
import binascii

binary_string = binascii.unhexlify(hex_string)

Read

binascii.unhexlify

Return the binary data represented by the hexadecimal string specified as the parameter.

rahul
This returns "binary" as in the actual bytes, but it does not convert it to a printable representation as "0" and "1".
Matt Good
http://docs.python.org/library/binascii.html is subtitled Convert between binary and ASCII. Doesn't that mean it returns a string?
pavium
Yes, it returns a string containing the bytes represented, e.g.>>> unhexlify("ab")"\xab"
Matt Good
A: 

unhexlify

Amarghosh
+1  A: 

Replace each hex digit with the corresponding 4 binary digits:

1 - 0001
2 - 0010
...
a - 1010
b - 1011
...
f - 1111
DmitryK
Or replace each pair of hex digits with the corresponding 8 binary digits, or replace each triplet of hex digits with the corresponding 12 binary digits ... or replace each 10 hex digits, with the corresponding 40 binary digits - Oops! back where we started!
pavium
+6  A: 
bin(int("abc123efff", 16))[2:]
Glenn Maynard
Note that this only works on Python 2.6 and 3.0
Matt Good
Oh, this also omits any leading '0's so it may need padded for this use.
Matt Good
@Matt: what leading zeros?
SilentGhost
If the input is "1a" this gives "11010", not "00011010" which may or may not be what you want.
Matt Good
There are an infinite number of leading zeroes on every number, so I'd hope it omits them.
Glenn Maynard
Heh there's finally a bin method?
Unknown
It's unfortunate that it's a global builtin. It should have been int.bin (int.oct, int.hex), instead of eating away at the global namespace.
Glenn Maynard
It's quite reasonable to need the leading zeros (and to not need them). You might want the null byte 0x00 to be eight zero bits for example - this is important for some applications. Also the OP has a leading zero in his example (but I suspect that's just random in this case!)
Scott Griffiths
A: 
John Montgomery
A: 
bin(0xabc123eff)[2:]
mshsayem
+1  A: 

Another way:

import math

def hextobinary(hex_string):
    s = int(hex_string, 16) 
    num_digits = int(math.ceil(math.log(s) / math.log(2)))
    digit_lst = ['0'] * num_digits
    idx = num_digits
    while s > 0:
     idx -= 1
     if s % 2 == 1: digit_lst[idx] = '1'
     s = s / 2
    return ''.join(digit_lst)

print hextobinary('abc123efff')
ChristopheD
This fails if hex_string is set to 'f0'
nailer
+1  A: 

hex --> decimal then decimal --> binary

#decimal to binary 
def d2b(n):
    bStr = ''
    if n < 0: raise ValueError, "must be a positive integer"
    if n == 0: return '0'
    while n > 0:
        bStr = str(n % 2) + bStr
        n = n >> 1    
    return bStr

#hex to binary
def h2b(hex):
    return d2b(int(hex,16))
Mat
A good solution for those stuck on Python 2.4
nailer