0

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.

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

3 Comments

I was thinking it'd be something like that, but can you explain to me how exactly this does it?
aligns it to the next 8-byte boundary with respect to d. For example, if d is 0x00000001 and w1 is 0x00000002, it would be aligned to 0x00000009, not 0x00000008
I just added the explanation above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.