← All problems · Bit Manipulation
Set All Bits in a Given Range
Set every bit from l to r inclusive, using 1-based positions (1 is the least significant bit). Preserve all other bits. For invalid ranges return x unchanged.
Implement uint32_t set_range(uint32_t x, unsigned l, unsigned r).
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.
Create a mask of r-l+1 ones and shift it by l-1.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <limits.h>
uint32_t set_range(uint32_t x, unsigned l, unsigned r)
{
if(l<1 || r>32 || l>r)return x;
uint32_t mask=(UINT32_MAX >> (32-(r-l+1))) << (l-1);
return x | mask;
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
#include <climits>
std::uint32_t set_range(std::uint32_t x, unsigned l, unsigned r)
{
if(l<1 || r>32 || l>r)return x;
std::uint32_t mask=(UINT32_MAX >> (32-(r-l+1))) << (l-1);
return x | mask;
}
OR sets the entire range. Using an all-ones unsigned mask avoids shifting by 32.
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(set_range(0,4,5)==24);
CHECK(set_range(1,4,5)==25);
CHECK(set_range(0,1,32)==UINT32_MAX);
CHECK(set_range(0,32,32)==0x80000000u);
CHECK(set_range(7,0,5)==7);
CHECK(set_range(7,5,4)==7);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}