Python 玩转 10进制 16进制相互转换

16进制转10进制(hex convert to int)

通过简单的int(hex),就可以把16进制转换成10进制数据

decimalism_number = int(0x10)

16进制字符串转10进制(string convert to int)

代码如下:

# by lingshunlab.com
hex_string = '0x66' # or '66'
print(hex_string)

decimalism_number =  int(hex_string, 16)
print(decimalism_number)

print(type(hex_string),  " to "  , type(decimalism_number))

image-20220707173916606

10进制 转 16进制字符串(int convert to hex String)

使用hex(int), 可以把10进制 转换成 以字符串的类型表达16进制

代码如下:

# by lingshunlab.com
decimalism_number = 66
decimalism_number_to_hex_string = hex(decimalism_number)
print(decimalism_number_to_hex_string)

代码运行的结果,如图:

image-20220707171933834

10进制 转换 16进制字符串表达式并自动补0(hex String fill 0)

# by lingshunlab.com
decimalism_number = 6
print(hex(decimalism_number)) # 以16进制表达
auto_fill_0_hex_string = ('%02X' %  decimalism_number) # 格式化自动补0
print(auto_fill_0_hex_string)

image-20220707211448270

10进制 转换 16进制字符串去0x (int convert to String)

代码如下:

# by lingshunlab.com
number_int = 66
print(hex(number_int)[2:],end=' ')

image-20220707211537895

字符 转 ASCII 码

代码如下:

# by lingshunlab.com
letter_str = 'g'
letter_hex = ord(letter_str)
print(letter_hex)

运行后如下图:

image-20220707211027556