Vishnu
Vishnu

Reputation: 324

Converting from hexadecimal to binary values

Am converting a value from hexadecimal to binary value.I used bin() of python like this:

value = 05808080
print bin(int(value, 16))

output i got is 0b101100000001000000010000000(output should be 32 bit)
output should be 0000 0101 1000 0000 1000 0000 1000 0000(correct output)

What is this 'b' in the output and how can i replace it with correct binary values.I think two values up here is almost same except issue with "b" in output.How will i resolve this ?

Upvotes: 3

Views: 21360

Answers (2)

user11034079
user11034079

Reputation: 21

def hex2bin(HexInputStr, outFormat=4):
    '''This function accepts the following two args.
    1) A Hex number as input string and
    2) Optional int value that selects the desired Output format(int value 8 for byte and 4 for nibble [default])
    The function returns binary equivalent value on the first arg.'''
    int_value = int(HexInputStr, 16)
    if(outFormat == 8):
        output_length = 8 * ((len(HexInputStr) + 1 ) // 2) # Byte length output i.e input A is printed as 00001010
    else:
        output_length = (len(HexInputStr)) * 4 # Nibble length output i.e input A is printed as 1010


    bin_value = f'{int_value:0{output_length}b}' # new style
    return bin_value

print(hex2bin('3Fa', 8)) # prints 0000001111111010

Upvotes: 1

tobias_k
tobias_k

Reputation: 82949

The output you get is correct, it just needs to be formatted a bit. The leading 0b indicates that it is a binary number, similarly to how 0x stands for hexadecimal and 0 for octal.

First, slice away the 0b with [2:] and use zfill to add leading zeros:

>>> value = '05808080'
>>> b = bin(int(value, 16))
>>> b[2:]
'101100000001000000010000000'
>>> b[2:].zfill(32)
'00000101100000001000000010000000'

Finally, split the string in intervals of four characters and join those with spaces:

>>> s = b[2:].zfill(32)
>>> ' '.join(s[i:i+4] for i in range(0, 32, 4))
'0000 0101 1000 0000 1000 0000 1000 0000'

If you can live without those separator spaces, you can also use a format string:

>>> '{:032b}'.format(int(value, 16))
'00000101100000001000000010000000'

Upvotes: 5

Related Questions