問題描述
我在像
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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!