Find maximum signed short integer in python

How to get the maximum signed short integer in Python (i.e. SHRT_MAX in C limits.h) ?

I want to normalize samples from one channel of a file *.wav, so instead of a bunch of 16-bit integers, I want a bunch of floats from 1 to -1. Here is what I have (the corresponding code is in the function normalized_samples()):

def samples(clip, chan_no = 0):
    # *.wav files generally come in 8-bit unsigned ints or 16-bit signed ints
    # python 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
source share
4 answers

in the sys module, sys.maxint. Although I'm not sure if this is the right way to solve your problem.

+1
source

GregS , . 8 16 , , .

, 16- int -32768 32767. 32767 < -1 .

:

yield float ( + 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

(.. , 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

+1

All Articles