python,从json对象(十六进制)到原始内部二进制字符串

时间:2012-05-25 16:19:09

标签: python json hex binary-data

在python中如何将“json-loaded”对象值转换为原始二进制字符串?即“0A”要转换为“1010”?

我所做的是以下内容: 从文件中读取一行,即假设该文件包含以下行:

{"hex":"0A01145af1ab"}

我读了它 然后我用json库加载它//好到目前为止

data = json.loads(a_line)

然后我可以使用数据[“hex”],

但我需要ie。 “0A”要转换为“1010”,我不知道该怎么做 我读了topic这与我的问题类似,但它没有帮助我(base64.b16decode(data [“hex”])返回错误)

非常感谢!

1 个答案:

答案 0 :(得分:2)

>>> bin(int(data['hex'][:2], 16))[2:]
'1010'

还要format(..., 'b')转换为二进制(不带0b前缀)