将十六进制转换为二进制

2022-01-09 00:00:00 python string binary string-formatting hex

问题描述

我有 ABC123EFFF.

I have ABC123EFFF.

我想要 001010101111000001001000111110111111111111(即二进制表示,例如,42 位数字和前导零).

I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).

怎么做?


解决方案

解决左侧尾随零问题:

my_hexdata = "1a"

scale = 16 ## equals to hexadecimal

num_of_bits = 8

bin(int(my_hexdata, scale))[2:].zfill(num_of_bits)

<小时>

它将给出 00011010 而不是修剪后的版本.


It will give 00011010 instead of the trimmed version.

相关文章