Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find maximum signed short integer in python

Tags:

python

struct

How do I get the maximum signed short integer in Python (i.e. SHRT_MAX in C's limits.h)?

I want to normalize samples from a single channel of a *.wav file, so instead of a bunch of 16-bit signed integers, I want a bunch of floats between 1 and -1. Here's what I've got (the pertinent code is in the normalized_samples() function):

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
like image 222
aaronstacy Avatar asked Feb 22 '10 01:02

aaronstacy


2 Answers

GregS is right, this is not the right way to solve the problem. If your samples are known 8 or 16 bit, you don't want to be dividing them by a number that varies by platform.

You may be running into trouble because a signed 16-bit int actually ranges from -32768 to 32767. Dividing by 32767 is going to give you < -1 in the extreme negative case.

Try this:

yield float(sample + 2**15) / 2**15 - 1.0

like image 72
ljp Avatar answered Sep 29 '22 11:09

ljp


Here is a way using 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
like image 38
John La Rooy Avatar answered Sep 29 '22 10:09

John La Rooy