如何在python中将字节字符串拆分为单独的字节 [英] How to split a byte string into separate bytes in python

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

问题描述

好的,所以我一直在使用 python 来尝试创建波形图像,我正在使用 song = wave.open().wav 文件从 .wav 文件中获取原始数据code> 和 song.readframes(1),返回:

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

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

解决方案

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

<预><代码>>>>值 = b'\x00\x01\x00\x02\x00\x03'>>>值[:2]b'\x00\x01'>>>值[2:4]b'\x00\x02'>>>值[-2:]b'\x00\x03'

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

<预><代码>>>>mv = memoryview(value).cast('H')>>>mv[0]、mv[1]、mv[2]256、512、768

mv 对象现在是一个内存视图,将每 2 个字节解释为一个无符号短整型;所以它现在的长度为 3,每个索引都是一个整数值,基于底层字节.

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'

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.

解决方案

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'

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

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中将字节字符串拆分为单独的字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆