136. Compile-Time Power-of-Two Validator

In high-performance embedded audio or signal processing, circular buffers often require their size to be a Power of Two (e.g., 32, 64, 128). This allows the expensive modulo operator (%) to be replaced with a fast bitwise AND operator (&) for index wrapping.

If a developer accidentally configures a buffer size that is not a power of two (e.g., 100), the bitwise logic will fail, leading to data corruption. This error must be caught at compile-time, not runtime.

Your task is to implement a Class Template named PowerOfTwoBuffer. It must accept one Non-Type Template Parameter:

  1. int Size: The capacity of the buffer.

The class must:

  1. Use static_assert to validate that Size is a power of two. Use the bitwise check: (Size > 0) && ((Size & (Size - 1)) == 0).
  2. Implement a method int getWrappedIndex(int raw_index) that returns the index wrapped using the bitwise mask: raw_index & (Size - 1).

Program Flow:

  1. The main function instantiates a PowerOfTwoBuffer with a fixed size of 16 (which is valid).
  2. Read integer N (number of test indices).
  3. Loop N times:
  4. Read integer raw_index.
  5. Call getWrappedIndex(raw_index).
  6. Print the result.

Input Format:

  • First line: Integer N.
  • Next N lines: Integer raw_index.
  • Input is provided via standard input (stdin).

Output Format:

  • For each index, print: Wrapped: <value>
  • Each output must be on a new line.

Example: 

Example 1 (Buffer Size = 16)

Input:

3
5
16
20

Output:

Wrapped: 5
Wrapped: 0
Wrapped: 4

Explanation:

  • 5 & 15 = 5
  • 16 & 15 = 0 (Wraps around)
  • 20 & 15 = 4 (20 is 16 + 4)

Constraints:

  • N range: 1 to 20
  • Size is fixed at 16 for the test cases (to ensure compilation).
  • Must use static_assert.
  • Must use & operator for wrapping (no %).

 

 

 

Loading...

Input

3 5 16 20

Expected Output

Wrapped: 5 Wrapped: 0 Wrapped: 4