2010-02-22 167 views
5

如何获得Python(即C的limits.h中的SHRT_MAX)中的最大符号短整数在Python中查找最大带符号短整数

我想正常化一个*.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 
+2

如果它们是16位样本,则将它们除以32768,无论最大的常规整数的大小是多少。 python只有两种整数,直到版本3,一个“常规”有限大小的int和一个无限的binint。没有短整型。 – 2010-02-22 01:32:26

回答

1

模块对称,所有的sys.maxint。虽然我不确定这是解决问题的正确方法。

+0

你会除以sys.maxint? – 2010-02-22 01:55:01

2

GregS是对的,这不是解决问题的正确方法。如果您的样本已知8位或16位,则不希望按照平台而变化的数字进行分割。

您可能会遇到麻烦,因为有符号的16位int实际上的范围是从-32768到32767.除以32767会给你< -1在极端否定的情况下。

尝试这种情况:

产量浮动(样品+ 2 ** 15)/ 2 ** 15 - 1.0

1

这里使用方式用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

我无法想象现代计算机上的情况(即,一个使用2的补整数),其中这会失败:

assert -32768 <= signed_16_bit_integer <= 32767 

要做到你要求什么了:

if signed_16_bit_integer >= 0: 
    afloat = signed_16_bit_integer/32767.0 
else: 
    afloat = signed_16_bit_integer/-32768.0 

看了你的代码有点更加紧密:你有sample_width_in_bytes所以才通过分255或256如果它是B和32768如果它是h