从Jython通过Java传递无符号值到C再返回
我参与了一个项目,目的是把C语言的API绑定到Jython(通过Java)。我们遇到了无符号值的问题,因为Java不支持无符号值。我们可以在Java和C之间进行类型转换,但从Jython到Java的转换就比较复杂了。
我在Python中写了一些“类型转换”函数。这些函数可以把表示有符号或无符号值的比特模式转换成表示相反符号的相同比特模式。
举个例子:
>>> u2s(0xFFFFFFFF)
-1L
>>> hex(s2u(-1))
'0xffffffffL'
有没有更优雅的方法来处理Jython和Java之间的这种符号转换?有没有人尝试过这样做?
这是整个模块的代码:
__all__ = ['u2s', 's2u']
def u2s(v,width=32):
"""
Convert a bit pattern representing an unsigned value to the
SAME BIT PATTERN representing a signed value.
>>> u2s(0xFFFFFFFF)
-1L
>>> u2s(0x7FFFFFFF)
2147483647L
"""
msb = int("1" + ((width - 1) * '0'), 2)
msk = int("1" * width, 2)
nv = v & msk
if 0 < (msb & nv):
return -1 * ((nv ^ msk) + 1)
else:
return nv
def s2u(v,width=32):
"""
Convert a bit pattern representing a signed value to the
SAME BIT PATTERN representing an unsinged value.
>>> hex(s2u(-1))
'0xffffffffL'
>>> hex(s2u(1))
'0x1L'
"""
msk = int("1" * width, 2)
if 0 > v:
return msk & (((-1 * v) ^ msk) + 1)
else:
return msk & v
if __name__ == "__main__":
import doctest
doctest.testmod()
我对我的代码和Jython中被接受的答案进行了性能测试。被接受的答案性能大约好1/3!我只测试了宽度明确指定的版本。
你可以用以下代码编辑我提供的代码,自己运行性能测试:
def _u2s(v, width=32):
fmt = {8: "B", 16: "H", 32: "I", 64: "Q"}[width]
return struct.unpack(fmt.lower(), struct.pack(fmt, v))[0]
def _s2u(v, width=32):
fmt = {8: "B", 16: "H", 32: "I", 64: "Q"}[width]
return struct.unpack(fmt, struct.pack(fmt.lower(), v))[0]
if __name__ == "__main__":
import doctest
doctest.testmod()
import time
x = range(-1000000,1000000)
t1 = time.clock()
y = map(s2u, x)
t2 = time.clock()
print t2 - t1
_t1 = time.clock()
z = map(_s2u, x)
_t2 = time.clock()
print _t2 - _t1
1 个回答
4
struct模块非常适合这个需求。
import struct
def u2s(v):
return struct.unpack("i", struct.pack("I", v))[0]
def s2u(v):
return struct.unpack("I", struct.pack("i", v))[0]
为了支持所有常见的宽度。
import struct
def u2s(v, width=32):
fmt = {8: "B", 16: "H", 32: "I", 64: "Q"}[width]
return struct.unpack(fmt.lower(), struct.pack(fmt, v))[0]
def s2u(v, width=32):
fmt = {8: "B", 16: "H", 32: "I", 64: "Q"}[width]
return struct.unpack(fmt, struct.pack(fmt.lower(), v))[0]
为了支持任何宽度,最多可以到64位。
import struct
def u2s(v, width=32):
return struct.unpack("q",struct.pack("Q",v<<(64-width)))[0]>>(64-width)
def s2u(v, width=32):
return struct.unpack("Q",struct.pack("q",v<<(64-width)))[0]>>(64-width)
如果你需要支持超过64位的宽度。
def u2s(v, width=32):
return v if v < (1L<<(width-1)) else v - (1L<<width)
def s2u(v, width=32):
return v if v >= 0 else v + (1L<<width)