Sign in to follow this  
DrTwox

28bits from 4 bytes?

Recommended Posts

Hello all. Once again I'm stuck and pulling out hair trying to work out how to process this number from an mp3 file header:
Quote:
From id3v2.3.0 Numbers preceded with $ are hexadecimal. The most significant bit (MSB) of a byte is called 'bit 7'. ... The ID3v2 tag size is encoded with four bytes where the most significant bit (bit 7) is set to zero in every byte, making a total of 28 bits. The zeroed bits are ignored, so a 257 bytes long tag is represented as $00 00 02 01
I read those four bytes into an unsigned int right? Then some kind of shift operation? The number is stored big endian; do I 'flip' it before or after processing? (My machine is little endian) I've tried to work it out on paper but I end up with either 192 or 258! Please save my hair! How do I do it?

Share this post


Link to post
Share on other sites
#include <iostream>

unsigned decode(unsigned char *s, unsigned n_bytes) {
unsigned result = 0;

for(unsigned i=0; i<n_bytes; ++i)
result = (result<<7) + s[i];

return result;
}

int main() {
unsigned char s[4]={0,0,2,1};
std::cout << decode(s,4) << std::endl;
}



The code above will work on machines of any endianness.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this