Question

What and why is the developer adding a hex value of 16, then using the bitwise operations AND followed by a NOT in this line:

size_t bytesPerRow = ((width * 4) + 0x0000000F) & ~0x0000000F;

He comments that "16 byte aligned is good", what does he mean?

 - (CGContextRef)createBitmapContext {
    CGRect boundingBox = CGPathGetBoundingBox(_mShape);

    size_t width = CGRectGetWidth(boundingBox);
    size_t height = CGRectGetHeight(boundingBox);
    size_t bitsPerComponent = 8;
    size_t bytesPerRow = ((width * 4) + 0x0000000F) & ~0x0000000F; // 16 byte aligned is good
Was it helpful?

Solution

ANDing with ~0x0000000F = 0xFFFFFFF0 (aka -16) rounds down to a multiple of 16, simply by resetting those bits that could make it anything other than a multiple of 16 (the 8's, 4's, 2's and 1's).

Adding 15 (0x0000000F) first makes it round up instead of down.

OTHER TIPS

purpose of size_t bytesPerRow = ((width * 4) + 0x0000000F) & ~0x0000000F; is to round up this value to 16 bytes

The goal is to set bytesPerRow to be the smallest multiple of 16 that is capable of holding a row of data. This is done so that a bitmap can be allocated where every row address is 16 byte aligned, i.e. a multiple of 16. There are many possible benefits to alignment, including optimizations that take advantage of it. Some APIs may also require alignment.

The code sets the 4 least significant bits to zero. If the value is an address it will be on an even 16 byte boundary, "16 byte aligned".

this ia a one's complement so

~0x0000000F 

becomes

0xFFFFFFF0

and-ing it with another value will clear 4 least significant bits.

This is the kind of thing we used to do all the time "back in the day"!

He's adding 0xf, and then masking out the lower 4 bits (& ~0xf), to make sure the value is rounded up. If he didn't add the 0xf, it would round down.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top