</>EmbeddedInterview
← All problems · Pointers & Strings

Check DMA Address Alignment

Easy

Return 1 if a is a nonzero power of two and addr is aligned to a bytes. Implement int aligned(uintptr_t addr, uintptr_t a).

Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Mask the address with alignment minus one.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>

int aligned(uintptr_t addr, uintptr_t a)
{
    return a && !(a & (a-1)) && !(addr & (a-1));
}

Aligned addresses have all offset bits clear.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    
    CHECK(aligned(0x1040,64)==1);
    CHECK(aligned(0x1041,64)==0);
    CHECK(aligned(0,0)==0);
    CHECK(aligned(12,3)==0);
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}