1

我正在解码 gsm 7 位,并从名为 noiam 的用户在此站点上找到了这段代码。

def gsm7bitdecode(f):
    f = ''.join(["{0:08b}".format(int(f[i:i+2], 16)) for i in range(0, len(f), 2)][::-1])
    return ''.join([chr(int(f[::-1][i:i+7][::-1], 2)) for i in range(0, len(f), 7)])

我的解码遇到了一个十字路口,因为它无助于解码带有偏移的消息。

如果有人可以帮助解释那段代码正在做什么以及如何更改它以解码偏移量为 1/2/3/etc(向前和向后)的消息,那么您将帮助我很多。

提前致谢!

4

1 回答 1

0

它是一个非常紧凑/高效的实现中的字符串解析。下面是展开后的样子:

'''
First Line: parse passed string:
For i initialized to 0, loop while i < length of f; step by 2 and assign i to
the reverse value in the list of values (so if len(f) = 10, i will be 
assigned to 8, 6, 4, 2, 0]
'''
f = ''
parsed_values = []
for i in range(0, len(f), 2)[::-1]: 
   # get substring of f from index i to i+2, [cast to base 16 int][3]
   temp = int(f[i:i+2], 16) 

   # convert the value "{0:08b}" to the value of temp and add it to the list
   parsed_values.append("{0:08b}".format(temp))

# finally, [stitch the parsed values together to make a single string][4]
f.join(parsed_values)

'''
Second Line:
Loop through values of parsed string; starting at index 0, step by 7, and
construct a return value out of the desired characters
'''
parsed_values = [] # reset parsed value array
for i in range(0, len(f), 7):
   # get the last char, the chunk (of length 7) that starts at i, and 
   # the last again. Cast to int base 2, convert to char
   temp = char(int(f[::-1][i:i+7][::-1], 2))

   # add to parsed value list
   parsed_values.append(temp)

return ''.join(parsed_values)

范围文档: http: //pythoncentral.io/pythons-range-function-explained/

扩展切片文档:https ://docs.python.org/release/2.3.5/whatsnew/section-slices.html

int 文档:https ://docs.python.org/2/library/functions.html#int

加入文档:https ://docs.python.org/2/library/stdtypes.html#str.join

于 2016-01-14T23:25:58.250 回答