Converting decimal to Formatted Binary and Hex - Python -


how convert decimal value formatted binary value , hex value

usually way

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

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

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

and need convert hex starting 0x

7   = 0x07 10  = 0x0a 250 = 0xfa  

alternative solution 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' 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -