Just out of curiosity while learning both wave file format and C++, I stumbled on this page that details the canonical layout of wave format
Now, I tried to write a C++ program to read out the sample rate
char buffer[4];
// already read other values before reading sample rate
inFile.read(buffer, 4);
// conversion using little endian
sampleRate = (long) buffer[0] + ((long) buffer[1] << 8) + ((long) buffer[2] << 16) + ((long) buffer[3] << 24);
In the hex editor, I can see my sample wave file has sample rate as 44 ac 00 00, which translates into 44100 rate. However, with the above code, I always end up with -21436
After some debugging, it turns out that the raw hex value “ac” should be translated into 172 in dec, but C++ assumed the hex value as “ffffffac”, which translates to -84 in dec. If C++ just assumes it is plain “ac”, I would have ended up with the correct sample rate value.
So the questions is, how do I read out the data from wave file and actually get the correct sample rate? Do I have to do some magic to strip away the leading “f”s ?
Thanks a bunch in advance!
There are two ways to fix your code. The first is to ensure that unsigned arithmetic is used throughout by making everything unsigned. The second is to use a bit mask to remove the sign extensions.