从十六进制转换为二进制不失0领先的蟒蛇 [英] Converting from hex to binary without losing leading 0's python

查看:180
本文介绍了从十六进制转换为二进制不失0领先的蟒蛇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像

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)

这篇关于从十六进制转换为二进制不失0领先的蟒蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆