且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-14 16:25:31

您可以对 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.