<0x00> 前言
处理二进制文件或者从网络接收字节流时,字节流中的结构化数据可能存在二进制有符号数。虽然开发者根据字节流协议可以先验的知道有符号数的字节序、字长、符号位等信息,但在使用Python进行类型转换时缺少将这些信息显式传递给Python解释器的手段。本文介绍了两种在Python开发中处理二进制有符号数的方法。<0x01> Python如何处理数字类型
很多编程语言在处理有符号数时将数字的最高位作为符号位,但Python的数字类型实现有所不同。以下是CPython中对长整形的定义:(以下皆为Python 2.7版本)include/longobject.h[cpp] view plain copy/ Long (arbitrary precision) integer object interface /
typedef struct _longobject PyLongObject; / Revealed in longintrepr.h /
include/longintrepr.h[cpp] view plain copy/* Long integer representation. The absolute value of a number is equal to
SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i)
Negative numbers are represented with ob_size < 0; zero is represented by ob_size == 0. In a normalized number, ob_digit[abs(ob_size)-1](the most significant digit) is never zero. Also, in all cases, for all valid i,
0 <= ob_d