从十六进制转换为二进制而不丢失前导0的python
- 作者: 你说无所谓的有所谓
- 来源: 51数据库
- 2022-10-25
问题描述
我在像
h = '00112233aabbccddee'
我知道我可以使用以下方法将其转换为二进制:
I know I can convert this to binary with:
h = bin(int(h, 16))[2:]
但是,这会丢失前导 0.有没有办法在不丢失 0 的情况下进行这种转换?或者最好的方法是在转换之前计算前导 0 的数量,然后在之后添加它.
However, this loses the leading 0's. Is there anyway to do this conversion without losing the 0's? Or is the best way to do this just to count the number of leading 0's before the conversion then add it in afterwards.
推荐答案
我认为没有办法默认保留这些前导零.
I don't think there is a way to keep those leading zeros by default.
每个十六进制数字转换为 4 个二进制数字,因此新字符串的长度应该是原始字符串大小的 4 倍.
Each hex digit translates to 4 binary digits, so the length of the new string should be exactly 4 times the size of the original.
h_size = len(h) * 4
然后,您可以使用 .zfill 将零填充到您想要的大小:
Then, you can use .zfill to fill in zeros to the size you want:
h = ( bin(int(h, 16))[2:] ).zfill(h_size)
推荐阅读
热点文章
Discord.py(重写)on_member_update 无法正常工作
0
Discord.py 在 vc 中获取用户分钟数
0
discord.py 重写 |为我的命令出错
0
Discord.py rewrite 如何 DM 命令?
0
播放音频时,最后一部分被切断.如何解决这个问题?(discord.py)
0
在消息删除消息 Discord.py
0
如何使 discord.py 机器人私人/直接消息不是作者的人?
0
(Discord.py) 如何获取整个嵌入内容?
0
Discord bot 尽管获得了许可,但不能提及所有人
0
Discord.py discord.NotFound 异常
0
