Python - 使用偏移量

时间:2016-01-14 10:48:25

标签: python sms offset gsm 7-bit

我正在解码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 /等(向前和向后)的消息,那么你会帮我解决很多问题。

提前致谢!

1 个答案:

答案 0 :(得分: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 docs:https://docs.python.org/2/library/functions.html#int

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