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
Post a Comment