简体   繁体   English

使用struct模块在python中将2位字符的字符串中的16位ASCII数据解码为整数时,如何将其解码?

[英]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?

Here is my code. 这是我的代码。 Ideally both struct.unpack and encode('hex') and changing it back to int should be the same right? 理想情况下,struct.unpack和encode('hex')都将其更改回int应该是正确的吗?

INPUT - 输入-

But, they are not the same in this case when you give a .wav file with nchannels = 1, samplewidth = 2, framerate = 44100, comptype = "None", compname = "Not compressed" 但是,当您给一个.wav文件提供nchannels = 1,samplewidth = 2,framerate = 44100,comptype =“ None”,compname =“ Not Compressed”时,它们是一样的

SAMPLE OUTPUT - 样品输出-

-15638 == eac2 == 27330 -15638 == eac2 == 27330

-15302 == 3ac4 == 15044 -15302 == 3ac4 == 15044

-14905 == c7c5 == 18373 -14905 == c7c5 == 18373

-14449 == 8fc7 == 4039 -14449 == 8fc7 == 4039

The left and right hand-side should be equal right? 左右手应该相等吧?

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('<h', frame)[0], ' == ',
    # struct.unpack(fmt, string) --- for more info about fmt -> https://docs.python.org/2/library/struct.html
    # If we it is two samples per frame, then we get a tuple with two values -> left and right samples

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

    if(value > 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()

The difference is between big-endian and little-endian encoding. 大端和小端编码之间的区别。

Your struct is big-endian, while the conversion with hex is little-endian. 您的结构是big-endian,而十六进制的转换是little-endian。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM