</>EmbeddedInterview
← All problems · Bit Manipulation

Isolate Lowest Active Interrupt Bit

Easy

Return a mask containing only the lowest set bit, or zero. Implement uint32_t lowest(uint32_t x).

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.

Use unsigned modular negation.

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

uint32_t lowest(uint32_t x)
{
    return x & (0u-x);
}

Unsigned negation and AND preserve only the lowest one.

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(lowest(0)==0);
    CHECK(lowest(12)==4);
    CHECK(lowest(0x80000000u)==0x80000000u);
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}