在Python中查找最大有符号短整型
我该如何在Python中获取最大有符号短整型整数(也就是C语言中的limits.h里的SHRT_MAX)?
我想对一个*.wav
文件的单声道样本进行归一化处理,所以我不想要一堆16位的有符号整数,而是想要一堆在1和-1之间的浮点数。以下是我写的代码(相关的代码在normalized_samples()
函数中):
def samples(clip, chan_no = 0):
# *.wav files generally come in 8-bit unsigned ints or 16-bit signed ints
# python's wave module gives sample width in bytes, so STRUCT_FMT
# basically converts the wave.samplewidth into a struct fmt string
STRUCT_FMT = { 1 : 'B',
2 : 'h' }
for i in range(clip.getnframes()):
yield struct.unpack(STRUCT_FMT[clip.getsampwidth()] * clip.getnchannels(),
clip.readframes(1))[chan_no]
def normalized_samples(clip, chan_no = 0):
for sample in samples(clip, chan_no):
yield float(sample) / float(32767) ### THIS IS WHERE I NEED HELP
5 个回答
2
GregS说得对,这不是解决问题的正确方法。如果你的样本是已知的8位或16位数据,你就不应该用一个会因平台不同而变化的数字去除它们。
你可能会遇到麻烦,因为一个有符号的16位整数的范围其实是从-32768到32767。用32767去除的话,在极端负数的情况下,结果会小于-1。
试试这个:
yield float(sample + 2**15) / 2**15 - 1.0
2
这里有一种使用cython的方法
getlimit.py
import pyximport; pyximport.install()
import limits
print limits.shrt_max
limits.pyx
import cython
cdef extern from "limits.h":
cdef int SHRT_MAX
shrt_max = SHRT_MAX
1
在模块 sys 中,有一个叫 sys.maxint 的东西。不过我不太确定这是不是解决你问题的正确方法。