2

I would like to convert a string into binary numbers using python 2.X

Input :  str = "4000ff11941859f3138e00000000673ac3b40047c0762b47818 ......"

     print type(str)
     >> <type 'str'>

Output should be : 0100000000001111000100011001010000011000101.......

     eg: 4 as 0100 
         f as 1111

Can some one suggest how to do this ? thanks in advance.

Kumar
  • 131
  • 1
  • 10

2 Answers2

0

I would do it like this:

str = '4000ff11941859f3138e00000000673ac3b40047c0762b47818'
print(bin(int(str, 16)))

Output:
    01000000000000001111111100010001100101000001100001011001111100110001001110001110000000000000000000000000000000000110011100111010110000111011010000000000010001111100000001110110001010110100011110000001100
WholesomeGhost
  • 1,101
  • 2
  • 17
  • 31
0

Here is a code sample.

You shouldn't use str as a variable name, it will override the built-in str() function. And you need to be careful about the length of the binary representations.

data = "a1ef4"
new_data=""

base = 16

# look at all characters in the string
for char in data:

    # convert to integer
    number = int(char, base)

    # convert to binary and then to string
    # the string has variable length
    # 4 becomes 100, not 0100
    binary = bin(number)
    binary_string = str(binary)

    # convert to string with fixed length
    binary_string = '{0:04b}'.format(number)

    # append to output data
    new_data += binary_string

# newdata == "10100001111011110100"
lhk
  • 27,458
  • 30
  • 122
  • 201