gdube
gdube

Reputation: 87

Unknown use of a pointer operation

I am currently trying to decipher someone else's code, and I've encountered something like this:

byte* d = new byte[n]; // Value of 'n' is determined at runtime.
byte* w1 = d + offset; // Value of 'offset' is constant and even.
...
for(int i = 0; i < imageCount; ++i){
    w1 += d - w1 & 7; // At this point, 'd' didnt change, and w1 > d.
    ...
}

I don't understand what the instruction in the loop does, and it's use.
The pointer 'w1' is used to write data to 'd' with an offset.
He then uses 'd' to write on the disk.

Upvotes: 0

Views: 54

Answers (1)

Joe Z
Joe Z

Reputation: 17936

This aligns w1 to the next 8-byte boundary relative to the start of d, staying put if w1 is already on that boundary.

w1 - d returns the current offset into d. Therefore d - w1 provides the negative of that.

Anding with 7 gives you a number 0 .. 7.

So how does adding that to w1 move w1 to the next 8-byte boundary? Suppose d was 1000. Let's look at what happens when w1 has the values 1001 through 1008. I'm going to add parentheses to make it clearer.

(1000 - 1001) = -1;  (-1) & 7 = 7;    
(1000 - 1002) = -2;  (-2) & 7 = 6;
(1000 - 1003) = -3;  (-3) & 7 = 5;
.... ok, this is getting tedious ....
(1000 - 1008) = -8;  (-8) & 7 = 0;

Now you'll notice that if you add the value produced to the starting value of w1, all 8 of these end on 1008. If you repeat this exercise with 1009 through 1016, you'll see the same thing happens there, rounding them all up to 1016.

Note that this is very specific to ptrdiff_t being a 2s complement number (which on just about every modern system, it is).

Upvotes: 3

Related Questions