Tianchi YU's Blog

What does [(size + 7) & !7] do?

Well, if you are familiar with the bits and related operations in computers, it should be quite visible.

This expression let size = (size + 7) & !7; is a common idiom used to align a value to the next multiple of 8 (which is often referred to as "rounding up to the nearest multiple of 8"). Let's break down what each part of the expression does:

  1. (size + 7) adds 7 to the original size. This is done to ensure that after the bitwise AND operation, the value is rounded up to the nearest multiple of 8.

  2. & !7 performs a bitwise AND operation with the bitwise complement of 7. In binary, the bitwise complement of 7 is represented as a sequence of 1s (111...111) with the same number of bits as 7. This operation effectively sets the three least significant bits to 0, ensuring that the value is aligned to the next multiple of 8.

For example, let's say size is initially 13:

So, the expression let size = (size + 7) & !7; takes the original size, adds 7 to it, and then clears the three least significant bits to ensure the result is rounded up to the next multiple of 8.

Voilà!

#G2K #programming