# C Program to Find the Position of 1-bits

«
»

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

Problem Description

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

Problem Solution

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

Program/Source Code

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);
}```
Program Explanation

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.

Note: Join free Sanfoundry classes at Telegram or Youtube

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.

Runtime Test Cases
```
\$ 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.

Take C Programming Mock Tests - Chapterwise!
Start the Test Now: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

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

If you wish to look at programming examples on all topics, go to C Programming Examples. 