1

How do i convert the decimal value into formatted Binary value and Hex value

usually i do it this way

  binary = lambda n: '' if n==0 else binary(n/2) + str(n%2)
  print binary(17)
  >>>> 10001

  print binary(250)
  >>>> 11111010

but i wanted to have 8 binary digits for any value given (0-255 only) i.e. I need to append '0' to the beginning of the binary number like the examples below

  7 = 0000 1111
 10 = 0000 1010
250 = 1111 1010

and even i need to convert to the hex starting with 0x

7   = 0x07
10  = 0x0A
250 = 0xFA 

4 Answers 4

2

Alternative solution is to use string.format

>>> '{:08b}'.format(250)
'11111010'
>>> '{:08b}'.format(2)
'00000010'
>>> '{:08b}'.format(7)
'00000111'
>>> '0x{:02X}'.format(7)
'0x07'
>>> '0x{:02X}'.format(250)
'0xFA'
Sign up to request clarification or add additional context in comments.

Comments

1

You can use the built-in functions bin() and hex() as follows:

In[95]: bin(250)[2:]
Out[95]: '11111010'

In[96]: hex(250)
Out[96]: '0xfa'

1 Comment

bin(2)[2:] will print 10 without leading zeroes
1

You can use bin(), hex() for binary and hexa-decimal respectively, and string.zfill() function to achieve 8 bit binary number.

>>> bin(7)[2:].zfill(8)
'00000111'
>>> bin(10)[2:].zfill(8)
'00001010'
>>> bin(250)[2:].zfill(8)
'11111010'
>>> 
>>> hex(7)
'0x7'
>>> hex(10)
'0xa'
>>> hex(250)
'0xfa'

I assume that leading 0's were not required in hexadecimals.

Comments

0

You can use format:

'{:08b}'.format(5)


'{:#x}'.format(12)

1 Comment

You should elaborate, maybe include the outputs of those expressions.

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.