2018年1月11日 星期四

Python: Convert decimal to hexadecimal

Python: Convert decimal to hexadecimal

Python Basic: Exercise-141 with Solution

Write a python program to convert decimal to hexadecimal.
Sample Solution:-
x = 30
print(x,'=',format(x, '02x'))
x = 4
print(x,'=',format(x, '02x'))

integer = 2
hex_string = '0x{:02x}'.format(integer)
print("2=",hex_string)

i=12
hex1= '0x' + hex(i)[2:].rjust(2, '0')
print('12=',hex1)

integer = 255
hex_string = format(integer, '#04x')  # add 2 to field width for 0x
print('255=',hex_string)

========== RESTART: F:/Python_APSC/py-ex-basic-141.py ============
30 = 1e
4 = 04
2= 0x02
12= 0x0c
255= 0xff
>>> 

沒有留言:

張貼留言