Comment

Comment by qb45

The correct solution for GCC is specifying 1-byte alignment for this particular array:

  #include <stdlib.h>
  #include <stdint.h>

  typedef uint32_t __attribute__((__aligned__(1))) uint32_t_unaligned;

  uint64_t sum (const uint32_t_unaligned * p, size_t nwords)
  {
      uint64_t res = 0;
      size_t i;
      for (i = 0; i < nwords; i++) res += p [i];
      return res;
  }
Probably works on clang too and IIRC the MS compiler provides similar functionality with different syntax. AFAIK there is no portable solution.

And I'm not sure how exactly this code will fail on architectures which don't support unaligned uint32_t.

parent qb45 10 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton