I am trying to read a flac file, and the format specifies that the sample rate is stored as a 20 bit number.
I have found the 3 bytes that this pertains to: 0x0A 0xC4 0x42
Now from online calculators, I have tested my AND operation to strip off the last 4 bits, because these are 8 bit bytes.
0x0AC442(hex) & 0xFFFFF0(hex) = 705600(dec), however, there are still 4 bits of 0 in there
705600(dec) = 10101100010001000000(bin)
I'm actually looking for it with those trimmed off
1010110001000100(bin) = 44100(dec)
So the sample rate I'm looking for is 44100 Hz or 44.1 kHz.
I'm having a really hard time doing this in C. Endianness and other factors are confusing the hell out of me.
Here is how I am trying it:
Code:
char num[9] = {0};
unsigned long sample_rate = 0; //sizeof on my system = 4
...
memcpy(&num, &data[pos], 3);//this copies the next 3 bytes of my buffer into a byte array
sample_rate = num[0] << 16 | num[1] << 8 | num[2]; //num[0] = 0x0A, num[1] = 0xC4, num[2] = 0x42
sample_rate = sample_rate & 0xFFFFF0
printf("Sample Rate = %lu\n", sample_rate);
This is giving me the result of "Sample Rate = 16761920", so I'm obviously doing something wrong.
Thanks for any help you guys can provide!