How to split a byte string into separate bytes in python

前端 未结 3 849
挽巷
挽巷 2020-12-02 23:00

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 so

3条回答
  •  借酒劲吻你
    2020-12-02 23:42

    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.

提交回复
热议问题