Python Forum
Four sequential bytes; Need to remove high order bit in each to get correct output - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Four sequential bytes; Need to remove high order bit in each to get correct output (/thread-32085.html)



Four sequential bytes; Need to remove high order bit in each to get correct output - GrandSean - Jan-20-2021

I am writing program to manipulate the contents of an .MP3 file. In reading the header in
binary(byte) mode, decoding the header Size field is giving me problems. See ID3.org. The definition
of the field is
ID3v2 size = 4 * %0xxxxxxx

I have been away from programming for about 15 years and need to relearn the basics.

Not looking for code here, just a pointer on how to remove 4 bits from the inside of the field.

Huh

Thanks,

GrandSean


RE: Four sequential bytes; Need to remove high order bit in each to get correct output - bowlofred - Jan-20-2021

So sounds like you want to treat the 4 bytes as a single 28-bit number. In that case I would:

* initialize total to zero
* starting with the high-order byte, loop over the four bytes
** shift the total left by 7 bits (total << 7)
** add the current byte & 127 to the total.


RE: Four sequential bytes; Need to remove high order bit in each to get correct output - GrandSean - Feb-06-2021

(Jan-20-2021, 05:00 AM)bowlofred Wrote: So sounds like you want to treat the 4 bytes as a single 28-bit number. In that case I would:

* initialize total to zero
* starting with the high-order byte, loop over the four bytes
** shift the total left by 7 bits (total << 7)
** add the current byte & 127 to the total.

Okay, I get the concept but am having a problems translating it to code.
Just to make sure we are on the same page, I read 4 consecutive bytes (total of 32 bits) from
a file and I need to make a 28 bit number by removing the most significant bit from each byte.


RE: Four sequential bytes; Need to remove high order bit in each to get correct output - deanhystad - Feb-06-2021

Quote:Example:

255 (%11111111) encoded as a 16 bit synchsafe integer is 383
(%00000001 01111111).

length_ss = 383
length_bytes = length_ss.to_bytes(4, 'big')
length = 0
for byte in length_bytes:
    length = length * 128 + byte
print(f'Synchsafe {length_ss} = integer{length}')



RE: Four sequential bytes; Need to remove high order bit in each to get correct output - bowlofred - Feb-06-2021

Here's someone that has coded up both encoding and decoding in python.

https://stuffivelearned.org/doku.php?id=misc:synchsafe


RE: Four sequential bytes; Need to remove high order bit in each to get correct output - GrandSean - Feb-06-2021

Thank you both for the pointers.

GrandSean