bsc

Comprehensive codebase and cou...
Log | Files | Refs | Activity | README | LICENSE

root / semester_1 / letusc / luc105.c

luc105.c (1033B)


      1 /* Write a function checkbits(x, p, n) which returns true if all 'n' bits starting from position 'p' are turned on.
      2 */
      3 /* Let Us C, Chap- 21 (Operations on Bits), Qn No.: B(c) */
      4 
      5 /* This file is auto-generated by a bot. */
      6 /* This code is not compiled; it is for reference only. */
      7 
      8 
      9 #include <stdio.h>
     10 #include <stdlib.h>
     11 
     12 int checkbits(unsigned int x, int p, int n);
     13 
     14 int main()
     15 {
     16     unsigned int x;
     17     int p, n;
     18 
     19     printf("Enter number (x): ");
     20     scanf("%u", &x);
     21     printf("Enter starting position (p) and count (n): ");
     22     scanf("%d %d", &p, &n);
     23 
     24     if (checkbits(x, p, n))
     25         printf("TRUE: %d bits starting at %d are ON.\n", n, p);
     26     else
     27         printf("FALSE: Not all specified bits are ON.\n");
     28 
     29     return 0;
     30 }
     31 
     32 int checkbits(unsigned int x, int p, int n)
     33 {
     34     unsigned int mask;
     35     
     36     // Create a mask of n 1s. E.g., if n=3, mask=000...0111
     37     mask = (1 << n) - 1;
     38     
     39     // Shift mask to position p
     40     mask = mask << p;
     41 
     42     // Check if bits in x match the mask
     43     return (x & mask) == mask;
     44 }
© notamitgamer • Site Built: 2026-09-05 01:53:16 UTC • git-mirror commit: c170d72 [view raw info]
Originally created with stagit • modified by notamitgamer
Forked from github.com/notamitgamer/git-mirror