从十六进制转换为二进制而不丢失前导0的python

Converting from hex to binary without losing leading 0#39;s python(从十六进制转换为二进制而不丢失前导0的python)
本文介绍了从十六进制转换为二进制而不丢失前导0的python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在像

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的python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)