If you want to flip a single bit, you probably want to manipulate the bits inside a single byte, not unpack it to a string, change characters, repack it as string, and then perform a conversion to byte again, as all of that wastes an incredible amount of time compared to just literally flipping a bit =)
- // load data
- byte[] data = loadBytes("file.in");
- // get the Nth byte
- byte b = data[n]
- // flip one of the eight bits, let's say the Mth
- byte flipbit = (byte) (1 << M);
- if(b>= flipbit) { b -= flipbit; } else { b += flipbit; }
- // and then save the result
- data[n] = b;
- saveBytes("file.out", data)
Note that we use (1 << ...) as the integer version of pow(2, ...) since every bit shift left raises by a power of two. M=0 gives us 1, M=1 gives 2, M=2 gives 4, M=3 gives 4, etc.
Conceptually, we're taking the byte, looking at its value, and see whether a certain bit is set by verifying that the value is greater or equal to the value that bit encodes in the byte. If the value's higher, unset that bit by subtracting the exact value that bit encodes. Otherwise, add that value so that the bit becomes set.
- Pomax