打印
[实用程序源码及工具软件]

Python语言下的inttohex()和hextoint()

[复制链接]
101|0
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
hotpower|  楼主 | 2023-9-18 22:43 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
#! -*- coding:utf-8 -*-
#菜农HotPower[url=home.php?mod=space&uid=516618]@163.com[/url] 2019.4.9 于西安雁塔菜地
def inttohex(v, size):
    return "{:>0{}X}".format(v,size)[-size:]
def hextoint(s):
    return int(s, 16)
i=0x0123456789aBcdeF
j=0x12Ab
s="fFFf"
print(inttohex(i, 5))
print(inttohex(j, 6))
print(inttohex(1234, 4))
print(inttohex(0x1234, 4))
print(hextoint(s))
print(hex(j))
运行结果:
BCDEF
0012AB
04D2
1234
65535
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

帖子

506

粉丝