How to calculate image bits

Hello, I am studying while watching imageCompressionExample.
I have a question while looking at this example.

if(ofGetKeyPressed('g')) {
			ofBuffer file = ofBufferFromFile(curFilename, true);
			int fileSize = file.size();
			char * buffer = file.getData();

			int whichByte = (int)ofRandom(fileSize * glitchStart, fileSize);

			int whichBit = ofRandom(8);
			char bitMask = 1 << whichBit;

			buffer[whichByte] |= bitMask;

What I have understood so far is that the size of the file and the bytes of the file (photo) are stored,

and the bit values belonging to random bytes are changed through operations.

Did I understand it well?

And…

char bitMask = 1 << whichBit;

buffer[whichByte] |= bitMask;

I wonder what this code means.

What does it mean to move 1 bit to the left by “whichBit” and then perform an “or operation” with a byte?

the shift left operator is used here to set the bits of the value.
So, a char has 8 bits.
Lets think that these are all zero;
0000 0000
pushing a 1 to the left looks like.
bit representation / operation

0000 0001 = 1 << 1;
0000 0010 = 1 << 2;
0000 0100 = 1 << 3;
0000 1000 = 1 << 4;
0001 0000 = 1 << 5;
0010 0001 = 1 << 6;

then

buffer[whichByte] |= bitMask;
// is the same as
buffer[whichByte] =  buffer[whichByte] | bitMask;

The or operation is done bitwise, bit by bit.
like this.

0001 | 1000 = 1001
0001 | 1100 = 1101
0001 | 0010 = 0011

If there is a 1 in any of the 2 operands make the corresponding bit 1. The resulting bit will only be zero when both of the operand bits are zero.

Oh, I know the meaning of the operator.

I wonder how the numbers that are calculated affect the picture as a result.

For example

char bitMask = 1 << whichBit;

Why 1 is calculated with whichBit, And

buffer [whichByte] |= bitMask;

I wonder what the intention of the creator of these codes is.

Probably just an aesthetic choice made by the author of that code. You can try different values and see what happens :smiley: that is what is so awesome about coding visual stuff, a lot of the times it is just trying out until you find something you like.
try
char bitMask = 2 << whichBit;
or what ever value. you can even try a variable value instead of a hard coded value.

buffer [whichByte] &= bitMask;
buffer [whichByte] ^= bitMask;

Try the different bitwise operators and see what happens.

Happy coding! :slight_smile:

Thank you for your answer.

I thought there was a certain formula. I get to look at it from a different perspective.

Well, it is very well defined how to manipulate bits and how these make up the data that is in an image. But since these are being manipulated randomly it does not make much sense to worry about such :slight_smile:

1 Like