Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a byte string into separate bytes in python

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.

like image 763
Razzad777 Avatar asked Nov 16 '13 22:11

Razzad777


People also ask

Can you slice bytes in Python?

We can slice bytearrays. And because bytearray is mutable, we can use slices to change its contents. Here we assign a slice to an integer list.

How do you decode bytes in Python?

Python bytes decode() function is used to convert bytes to string object. Both these functions allow us to specify the error handling scheme to use for encoding/decoding errors. The default is 'strict' meaning that encoding errors raise a UnicodeEncodeError.

What does bytes () do in Python?

Python bytes() Function The bytes() function returns a bytes object. It can convert objects into bytes objects, or create empty bytes object of the specified size.


1 Answers

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.

like image 119
Martijn Pieters Avatar answered Sep 24 '22 02:09

Martijn Pieters