我需要在Python中将unicode字符串转换为其他类型,如无符号和有符号int 8位,无符号和有符号int 16位,无符号和有符号int 32位,无符号和有符号int 64位,双精度,浮点数,字符串,无符号和有符号8位,无符号和有符号16位,无符号和有符号32位,无符号和有符号64位。
我需要你们的帮助。
发布于 2008-12-17 11:58:57
使用int()将字符串转换为整数。Python没有不同的固定宽度整数,所以您只能得到一种类型的内容。
然后使用struct将整数打包成固定宽度:
res = struct.pack("=B",i) ## uint8_t
res = struct.pack("=b",i) ## int8_t
res = struct.pack("=H",i) ## uint16_t
res = struct.pack("=h",i) ## int16_t
res = struct.pack("=I",i) ## uint32_t
res = struct.pack("=i",i) ## int32_t
res = struct.pack("=Q",i) ## uint64_t
res = struct.pack("=q",i) ## int64_t
res = struct.pack("=f",i) ## float
res = struct.pack("=d",i) ## doublestruct生成一个包含二进制数字的字节字符串。
编辑:从评论中听起来你只是想把字符串(十进制数字)转换成一个整数。只需使用int(),但是您不会得到指定类型的所有复杂的溢出/下溢语义。你不能用python重现它,至少在不写大量代码的情况下是不行的。
我认为,如果你需要更多的帮助,你必须更准确地说明你想要实现的目标。
https://stackoverflow.com/questions/374318
复制相似问题