問題描述
我在像
h = '00112233aabbccddee'
我知道我可以使用以下方法將其轉(zhuǎn)換為二進(jìn)制:
I know I can convert this to binary with:
h = bin(int(h, 16))[2:]
但是,這會(huì)丟失前導(dǎo) 0.有沒有辦法在不丟失 0 的情況下進(jìn)行這種轉(zhuǎn)換?或者最好的方法是在轉(zhuǎn)換之前計(jì)算前導(dǎo) 0 的數(shù)量,然后在之后添加它.
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.
推薦答案
我認(rèn)為沒有辦法默認(rèn)保留這些前導(dǎo)零.
I don't think there is a way to keep those leading zeros by default.
每個(gè)十六進(jìn)制數(shù)字轉(zhuǎn)換為 4 個(gè)二進(jìn)制數(shù)字,因此新字符串的長(zhǎng)度應(yīng)該是原始字符串大小的 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)
這篇關(guān)于從十六進(jìn)制轉(zhuǎn)換為二進(jìn)制而不丟失前導(dǎo)0的python的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!