[实用程序源码及工具软件] Python语言下的inttohex()和hextoint()

[复制链接]
 楼主| hotpower 发表于 2023-9-18 22:43 | 显示全部楼层 |阅读模式
  1. #! -*- coding:utf-8 -*-
  2. #菜农HotPower[url=home.php?mod=space&uid=516618]@163.com[/url] 2019.4.9 于西安雁塔菜地
  3. def inttohex(v, size):
  4.     return "{:>0{}X}".format(v,size)[-size:]
  5. def hextoint(s):
  6.     return int(s, 16)
  7. i=0x0123456789aBcdeF
  8. j=0x12Ab
  9. s="fFFf"
  10. print(inttohex(i, 5))
  11. print(inttohex(j, 6))
  12. print(inttohex(1234, 4))
  13. print(inttohex(0x1234, 4))
  14. print(hextoint(s))
  15. print(hex(j))
  1. 运行结果:
  2. BCDEF
  3. 0012AB
  4. 04D2
  5. 1234
  6. 65535
  7. 0x12ab
可以看到,Python自带的hex()真没多大用处,故必须自己搞一个inttohex()

在实际应用中,实际上特别需要补0和固定位数。

测试发现,str.format()中{}竟然可嵌套!!!

"{:>0{}X}".format(v,size)[-size:]

上句表示数据右对齐裁剪,左边补0,字母A-F大写。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

个人签名:[url=http://www.21ic.com/tools/HotWC3_V1.23.html]

1460

主题

21619

帖子

508

粉丝
快速回复 在线客服 返回列表 返回顶部
个人签名:[url=http://www.21ic.com/tools/HotWC3_V1.23.html]

1460

主题

21619

帖子

508

粉丝
快速回复 在线客服 返回列表 返回顶部