3

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 ?

2
  • 1
    Is value a string? If I enter it as an int, without ', I get SyntaxError, because an octal number (starting with 0 can not contain an 8. Commented Feb 23, 2016 at 9:28
  • "TypeError: int() can't convert non-string with explicit base" Commented Jun 11, 2023 at 21:39

2 Answers 2

5

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'
Sign up to request clarification or add additional context in comments.

Comments

1
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.