How to decode a 16-bit ASCII data to an integer when you have it in a string of 2 characters in python using struct module?
<p>Here is my code. <strong>Ideally both struct.unpack and encode('hex') and changing it back to int should be the same right?</strong></p>

<p>INPUT -</p>

<blockquote>
  <p>But, they are <strong>not</strong> the same in this case when you give a .wav file with nchannels = 1, samplewidth = 2, framerate = 44100, comptype = "None", compname = "Not compressed"</p>
</blockquote>

<p>SAMPLE OUTPUT -</p>

<blockquote>
  <p>-15638  ==  eac2  ==  27330</p>
  
  <p>-15302  ==  3ac4  ==  15044</p>
  
  <p>-14905  ==  c7c5  ==  18373</p>
  
  <p>-14449  ==  8fc7  ==  4039</p>
  
  <p><em>The left and right hand-side should be equal right?</em></p>
</blockquote>

<pre><code>import wave
import sys
import struct

audiofile = wave.open(sys.argv[1], 'r')
# reading a file (normal file open)

print audiofile.getparams()
# (nchannels, sampwidth, framerate, nframes, comptype, compname)

for i in range(audiofile.getnframes()):
    frame = audiofile.readframes(1)
    # reading each frame (Here frame is 16 bits [.wav format of each frame])

    print struct.unpack('&lt;h', frame)[0], ' == ',
    # struct.unpack(fmt, string) --- for more info about fmt -&gt; https://docs.python.org/2/library/struct.html
    # If we it is two samples per frame, then we get a tuple with two values -&gt; left and right samples

    value = int(frame.encode('hex'), 16)
    # getting the 16-bit value [each frame is 16 bits]

    if(value &gt; 32767):
        value -= 2**16
    # because wav file format specifies 2's compliment as in even the negative values are there

    print frame.encode('hex') , ' == ', value

audiofile.close()
</code></pre>

<p>The difference is between big-endian and little-endian encoding.</p>

<p>Your struct is big-endian, while the conversion with hex is little-endian.</p>

python codec wave