长整型与字符串的二进制转换
有没有什么库可以把很长的数字转换成字符串,而不改变数据本身?
这些一行代码的方法太慢了:
def xlong(s):
return sum([ord(c) << e*8 for e,c in enumerate(s)])
def xstr(x):
return chr(x&255) + xstr(x >> 8) if x else ''
print xlong('abcd'*1024) % 666
print xstr(13**666)
6 个回答
2
其实,我发现自己对long(s,256)这个东西不太了解。我观察了一下,发现Python的CAPI文件“longobject.h”里有两个函数:
PyObject * _PyLong_FromByteArray( const unsigned char* bytes, size_t n, int little_endian, int is_signed);
int _PyLong_AsByteArray(PyLongObject* v, unsigned char* bytes, size_t n, int little_endian, int is_signed);
这两个函数可以完成相关的工作。我不太明白为什么它们没有被包含在某些Python模块里,如果我说错了,请纠正我。
2
这样怎么样
from binascii import hexlify, unhexlify
def xstr(x):
hex = '%x' % x
return unhexlify('0'*(len(hex)%2) + hex)[::-1]
def xlong(s):
return int(hexlify(s[::-1]), 16)
我没有计时,但这个方法应该会更快,而且可以处理更大的数字,因为它不使用递归。
4
你需要使用结构体模块。
packed = struct.pack('l', 123456)
assert struct.unpack('l', packed)[0] == 123456