I wrote this function to remove the most significant bit in every byte. But this function doesn't seem to be working the way I wanted it to be.
The output file size is always '0', I don't understand why nothing's been written to the output file. Is there a better and simple way to remove the most significant bit in every byte??
I won't go through your entire answer to provide your reworked code, but removing the most significant bit is easy. This comes from the fact that the most significant bit can easily be found by using log base 2 converted to an integer.
Output:
As such, 4387 in binary is 1000100100011 with a most significant bit at 12.
Likewise, 291 in binary is 0000100100011 with a most significant bit at 8.
In relation to shift operators, section 6.5.7 of the C standard says:
So firstly, remove
nBuffer << 8;
. Even if it were well defined, it wouldn't be an assignment operator.As people have mentioned, you'd be better off using
CHAR_BIT
than 8. I'm pretty sure, instead of0x7f
you meanUCHAR_MAX >> 1
and instead of 7 you meantCHAR_BIT - 1
.Let's just focus on nBuffer and bit_count, here. I shall comment out anything that doesn't use either of these.
At the end of this code, what is the value of nBuffer? What about bit_count? What impact would that have on your second loop?
while (bit_count > 0)
Now let's focus on the commented out code:
Where are you assigning a value to bit_buf? Using an uninitialised variable is undefined behaviour.
Instead of going through all of the bits to find the high one, this goes through only the
1
bits.high()
returns the high bit of the argument, or zero if the argument is zero.