如何在python中将字节字符串拆分为单独的字节

如何在python中将字节字符串拆分为单独的字节

本文介绍了如何在python中将字节字符串拆分为单独的字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,所以我一直在使用python尝试创建波形图像,并且正在使用song = wave.open()song.readframes(1).wav文件中获取原始数据,该返回的结果是:

Ok so I've been using python to try create a waveform image and I'm getting the raw data from the .wav file using song = wave.open() and song.readframes(1), which returns :

b'\x00\x00\x00\x00\x00\x00'

我想知道的是如何将其拆分为三个单独的字节,例如b'\x00\x00'b'\x00\x00'b'\x00\x00',因为每个帧的宽度为3个字节,所以我需要每个单独字节的值才能形成波形.我相信这就是我需要这样做的方式.

What I want to know is how I split this into three separate bytes, e.g. b'\x00\x00', b'\x00\x00', b'\x00\x00' because each frame is 3 bytes wide so I need the value of each individual byte to be able to make a wave form. I believe that's how I need to do it anyway.

推荐答案

您可以在byte对象上使用切片:

You can use slicing on byte objects:

>>> value = b'\x00\x01\x00\x02\x00\x03'
>>> value[:2]
b'\x00\x01'
>>> value[2:4]
b'\x00\x02'
>>> value[-2:]
b'\x00\x03'

但是,在处理这些框架时,您可能还想了解 memoryview()对象;这些使您可以将字节解释为C数据类型,而无需进行任何额外的工作,只需在基础字节上投射视图"即可:

When handling these frames, however, you probably also want to know about memoryview() objects; these let you interpret the bytes as C datatypes without any extra work on your part, simply by casting a 'view' on the underlying bytes:

>>> mv = memoryview(value).cast('H')
>>> mv[0], mv[1], mv[2]
256, 512, 768

mv对象现在是一个内存视图,将每2个字节解释为一个无符号的short;因此它现在的长度为3,并且每个索引都是基于基础字节的整数值.

The mv object is now a memory view interpreting every 2 bytes as an unsigned short; so it now has length 3 and each index is an integer value, based on the underlying bytes.

这篇关于如何在python中将字节字符串拆分为单独的字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:01