basics · beginner · ~15 min

Read a bit

Extract the value of a single bit.

Challenge

Implement:

int get_bit(unsigned x, int i);

Return bit i (0 or 1) of x. i is in 0..31.

Input format

x and a bit index i (0..31).

Output format

0 or 1.

Constraints

i in 0..31.

Starter code

#include <stddef.h>
/* Return bit i (0 or 1) of x. i in 0..31. */
int get_bit(unsigned x,int i){ (void)x;(void)i; return 0; }

Common mistakes

Forgetting to mask with & 1 (returning the whole shifted value).

Edge cases to handle

Bit 0 is the least-significant bit; bit 31 the most-significant.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.