Skip to content

Instantly share code, notes, and snippets.

@JonathonReinhart
Created November 26, 2014 00:50
Show Gist options
  • Save JonathonReinhart/15f60284f391ee7e05f3 to your computer and use it in GitHub Desktop.
Save JonathonReinhart/15f60284f391ee7e05f3 to your computer and use it in GitHub Desktop.
// unaligned.h
// Safely access unaligned multi-byte values (e.g on ARM)
// Jonathon Reinhart
// The use of 'packed' forces the compiler to assume no better
// than 1-byte alignment, and issue sequential byte reads/writes.
typedef union __attribte__((packed)) {
int16_t int16;
uint16_t uint16;
int32_t int32;
uint32_t uint32;
int64_t int64;
uint64_t uint64;
} unaligned_t;
static void read_uint32(const void *p)
{
return ((unaligned_t*)p)->uint32;
}
static void write_uint32(void *p, uint32_t val)
{
((unaligned_t*)p)->uint32 = val;
}
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment