本文介绍了Python中,如何去code二进制codeD十进制(BCD)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

二进制领域的描述是:

主叫号码,以com pressed BCD code pssed前$ P $,和剩余位填充0xF的

我曾尝试与结构格式16C打印和获取:('3','\\ X00','\\ X02 ','\\ X05','\\ X15','\\ X13','G','O','\\ XFF','\\ XFF','\\ XFF','\\ XFF','\\ XFF', '\\ XFF','\\ XFF','\\ XFF'),如果我用16B我得到 (51,0,2,5,21,19,71,79,-1,-1,-1,-1,-1,-1,-1,-1)。而且这是不正确的,我应该得到的电话号码,并且以上数字是无效的。

I have tried to print with struct format '16c' and I get: ('3', '\x00', '\x02', '\x05', '\x15', '\x13', 'G', 'O', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff') and if I use '16b' i get (51, 0, 2, 5, 21, 19, 71, 79, -1, -1, -1, -1, -1, -1, -1, -1). And it is not correct, I should get phone number, and numbers above are invalid.

print struct.unpack_from('>16b', str(data.read()),offset=46)

以上是code没有工作,我得到无效的数字。用什么格式,我应该解包16字节的领域,如何转换BCD code?

Above is code that didn't work and I get invalid numbers. With what format should I unpack that 16 byte field and how to convert BCD code ?

推荐答案

BCD codeS每号4位,并且通常带code只有0数字工作2号,1元4比特的信息。

BCD codes work with 4 bits per number, and normally encode only the digits 0 - 9. So each byte in your sequence contains 2 numbers, 1 per 4 bits of information.

以下方法使用一个发电机来产生这些数字;我假设一个0xF的值意味着没有更多的数字遵循:

The following method uses a generator to produce those digits; I am assuming that a 0xF value means there are no more digits to follow:

def bcdDigits(chars):
    for char in chars:
        char = ord(char)
        for val in (char >> 4, char & 0xF):
            if val == 0xF:
                return
            yield val

这里我用一个移动左大多数4位到右侧,并且选择了正确的 - 大多数4位。

Here I use a right-shift operator to move the left-most 4 bits to the right, and a bitwise AND to select just the right-most 4 bits.

示范:

>>> characters = ('3', '\x00', '\x02', '\x05', '\x15', '\x13', 'G', 'O', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff')
>>> list(bcdDigits(characters))
[3, 3, 0, 0, 0, 2, 0, 5, 1, 5, 1, 3, 4, 7, 4]

该方法适用于在 C 输出;你可以跳过 ORD 调用该方法,如果你直接传递整数(但使用 B 无符号的变种来代替)。或者,你可以只直接从您的文件中读出那些16个字节,并直接使用无需申请结构这个功能对那些字节。

The method works with the c output; you can skip the ord call in the method if you pass integers directly (but use the B unsigned variant instead). Alternatively, you could just read those 16 bytes straight from your file and apply this function to those bytes directly without using struct.

这篇关于Python中,如何去code二进制codeD十进制(BCD)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 08:20