user2345
user2345

Reputation: 537

Converting decimal to Formatted Binary and Hex - Python

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 

Upvotes: 1

Views: 1260

Answers (4)

user5449023
user5449023

Reputation:

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.

Upvotes: 1

Konstantin
Konstantin

Reputation: 25329

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'

Upvotes: 2

elzell
elzell

Reputation: 2306

You can use format:

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


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

Upvotes: 0

gtlambert
gtlambert

Reputation: 11961

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'

Upvotes: 1

Related Questions