title: Find next aligned memory address
body: <p>From my understanding of <a href="https://en.wikipedia.org/wiki/Data_structure_alignment#Computing_padding" rel="nofollow">wikipedia</a>, I can find the index of the next closest element with correct alignment by the following bitwise operation.</p>
  
  <pre><code>Assuming the address of the 1st element has the correct alignment.
  Assuming the index_alignment is a power of 2.
  new_index = (current_index + index_alignment - 1) &amp; ~(index_alignment - 1).
  new_address = address_of_1st_element + new_index
  index_alignment is 16 bytes/sizeof(type of element) for SSE.
  </code></pre>
  
  <p>Is it possible to use this directly on an address to find the next closest aligned address from any given address? (is this way quicker?)</p>
  
  <p>I was thinking about the following to do this quickly.</p>
  
  <pre><code>new_address = (current_address + alignment - 1) &amp; ~(alignment -1)
  alignment here is 16 for SSE.
  </code></pre>
  
  <p>When I implement this, I found the following code can't compile...</p>
  
  <p>Code fixed with Salva and Rotem's suggestions</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;stdint.h&gt;
  #define ALIGNMENT 16
  using namespace std;
  uint32_t* fix_ptr(uint32_t* ptr){
      return (uint32_t*)(
          (uintptr_t(ptr) + uintptr_t(ALIGNMENT) - 1)
          &amp;~ uintptr_t(ALIGNMENT - 1)
          );
  }
  void print_ptr (uint32_t* ptr){
      cout &lt;&lt; (long long)(void*)ptr &lt;&lt; endl;
  }
  
  void test(uintptr_t ptr_as_int){
      uint32_t* ptr1 = (uint32_t*) ptr_as_int;
      cout &lt;&lt; "Initial address: ";
      print_ptr(ptr1);
      uintptr_t alignment = ALIGNMENT;
      cout &lt;&lt; "    alignment: " &lt;&lt; alignment &lt;&lt; endl;
      cout &lt;&lt; "    alignment - 1: " &lt;&lt; (alignment - 1) &lt;&lt; endl;
      cout &lt;&lt; "    alignment &amp; alignment: " &lt;&lt; (alignment &amp; alignment) &lt;&lt; endl;
  
      uint32_t* ptr_fixed = fix_ptr(ptr1);
      cout &lt;&lt; "    fixed address: ";
      print_ptr(ptr_fixed);
  }
  int main(void){
      test(1000);
      test(16);
  }
  </code></pre>
  
  <p>Output (compiled with g++ code.cpp)</p>
  
  <pre><code>Initial address: 1000
      alignment: 16
      alignment - 1: 15
      alignment &amp; alignment: 16
      fixed address: 1008
  Initial address: 16
      alignment: 16
      alignment - 1: 15
      alignment &amp; alignment: 16
      fixed address: 16
  </code></pre>
  
  <p>1000 becomes 1008 and 16 becomes 16 as expected. Probably ok for my current use. Don't know if there are faster ways.</p>
  
  <p>Thanks.</p>