This is a C Program to find the position of string of 1-bits in a number for a given length.

This C Program finds the position of string of 1-bits in a number for a given length.

Take input from the user and finds string position as shown in the program below.

Here is source code of the C Program to find the position of string of 1-bits in a number for a given length. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

/* * C Program to Find the Position of String of 1-bits in a Number * for a given Length */ #include <stdio.h> void main() { int n, len, pos = 0, i = 0, count = 0; printf("**Finding the position of 1-bits in a number for given length**\n"); printf("enter a number\n"); scanf("%d", &n); printf("enter the length\n"); scanf("%d", &len); while (i <= 32) { if ((n & 1) == 1) //checking whether there is a 1-bit in the current position { count++;//counting the consecutive 1's in the integer pos = i; if (count == len) //checking whether the length matches { break; } } if ((n & 1) == 0) { count = 0; } n = n>>1; i++; } printf("the position of 1 in the string : %d\n", pos); }

In this C Program, we are reading the number and length using ‘n’ and ‘len’ variables respectively. Using while loop assign the position of strings of 1-bits in a number for a given length. If condition statement is used to check that there is a 1-bit in the current position. If the condition is true, then it will execute the statement for counting the consecutive 1’s in the integer.

Another if condition statement is used for checking whether the length matches. Another if condition statement is used to check whether there is a 1-bit in the starting position. If the condition is true then execute the statement.

Using Binary Right shift operator, the left operand’s value is moved right by the number of bits specified by the right operands and assign the value to n variable then count the consecutive 1’s in the integer. Print the position of string of 1-bits in a number for a given length.

$ cc bit7.c $ a.out **Finding the position of 1-bits in a number for given length** enter a number 10000 enter the length 3 the position of 1 in the string : 10 $ a.out enter a number 700 enter the length 4 the position of 1 in the string : 5

**Sanfoundry Global Education & Learning Series – 1000 C Programs.**

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

**If you find any mistake above, kindly email to [email protected]**

**Related Posts:**

- Watch Advanced C Programming Videos
- Check Computer Science Books
- Apply for C Internship
- Practice Computer Science MCQs
- Practice BCA MCQs