nixahn
nixahn

Reputation: 110

image processing bitwise instruction conceptual interpretation

the code comes from a Qt library that helps produce buttons with the shape of an image; it scans through all lines y and all the width x, generating the following change when the rgb part of the pixel coincides with the masking one (mp is the pointer at the start of the line and it is prefilled with 0xff):

*(mp + (x >> 3)) &= ~(1 << (x & 7));

I can't really interpret it; anyone with background to give a hand?

Upvotes: 0

Views: 731

Answers (2)

nixahn
nixahn

Reputation: 110

for the mortals; ok, background: http://www.cprogramming.com/tutorial/bitwise_operators.html; &= means we are gonna do a bitwise multiplication; in the rhs, the ~ is for the complement, so it flips 1s with 0s and viceversa; 7 in binary has 3 ones in the end and all zeros at front, so x & 7 preserves the last 3 bits in x; combined with << this will move the 1 in the first bit from the char 1 to the left a certain number of places in accordance with the exponent; since the exponent is only using the last 3 bits of x, it is smaller than 8(2^3); so the bit with the one will get in the position 1-8 within the 8 bits of the char; the flip ~ will turn the thing into all 1s except in that magic position; the multiplication performed by the &= will preserve everything in the lhs except that one bit. now for the lhs; we are kicking the last byte or the last 3 bits of x out with >> in a right shift operation; this means the location we'll modify the same byte (char type of mp) for every 8 increments of x; when we "jump", we'll do so by only one byte; when x=9 it will go to mp+1, when x= 17 it will go to mp+2; so it is like x/2^3 in integer operations, but in one shift operation; ok, now we have the elements to understand the whole thing;

tmask has been prefilled with 0xff, all ones; which means that it will be passive upon the &= operation, preserving what the rhs dictactes; this means that in case the there's a hit in an if statement that checks if the particular pixel is equal to the background, then this line is executed and we will wipe the specific bit related to the pixel;

Upvotes: 0

BitBank
BitBank

Reputation: 8725

From the looks of the code, mp points to the current line of a 1 bit per pixel image. The code clears the bit representing the pixel at X. It converts the X offset into a byte offset (x >> 3) and then logical AND's the byte with a mask created from the inverse 1 shifted left by the X position within the byte.

Upvotes: 1

Related Questions