给定一个32位有符号整数
Problem statement: Write a C program to find the Highest Bit Set for any given Integer.
问题陈述:编写C程序以查找任何给定Integer的最高位集 。
Solution: We can use bitwise operator here to solve the problem.
解决方案:我们可以在这里使用按位运算符来解决问题。
Pre-requisite: Input number n
前提条件 :输入数字n
Algorithm:
算法:
1) Set count=0 & store= -1
2) Do bit wise AND between n and 1.
n & 1
let n be a7a6a5a4a3a2a1a0
1->00000001
So doing bitwise AND (refer to published article on bitwise operators)
will result in all bits 0 except the LSB which will be a0.
If a0 is 1 then it is set, else not set.
If a0 is 1 then the bitwise AND results in 00000001 (1) else 00000000 (0)
Thus,
IF
n& 1 ==1 //current bit is set
update store to current count value.
END IF
3) count++;
4) Right shift n by 1
n = n >> 1
5) IF n==0
Break
ELSE
REPEAT step 2, 3, 4
6) IF store==-1
No set bit
Else
Print store
Example with Explanation:
解释示例:
Highest set bit in 12 (0-index based position, i.e., LSB is 0th bit): 12 → 00001100
12中的最高设置位(基于0索引的位置,即LSB为第 0位):12→00001100
Initially,
Count=0
Store=-1
So first iteration:
n=12 //00001100
n& 1 =0
store=-1
count=1
n=n>>1 (n=6) //00000110
So second iteration:
n=6 //00000110
n& 1 =0
store=-1
count=2
n=n>>1 (n=3) //00000011
So third iteration:
n=3 //00000011
n& 1 =1
store=2
count=3
n=n>>1 (n=1) //00000001
So fourth iteration:
n=1 //00000001
n& 1 =1
store=3
count=4
n=n>>1 (n=0) //00000000
program terminates
Print store, 3
Highest bit set: 3
C implementation
C实现
#include <stdio.h>
int main()
{
unsigned int n;
printf("enter the integer\n");
scanf("%d",&n);
int count=0,store=-1;
while(n!=0){
if(n & 1 == 1) //if current bit is set
store=count; //update store
n=n>>1; //right shift
count++; //increase count
}
if(store==-1){//if store not updated
printf("No bit is set\n"); //no set bit present at all
return 0;
}
printf("Highest bit set ");
//printing highest set bit
printf("in its binary representation: %d \n",store);
return 0;
}
Output
输出量
enter the integer
12
Highest bit set in its binary representation: 3
翻译自: https://www.includehelp.com/c-programs/find-the-highest-bit-set-for-any-given-integer.aspx
给定一个32位有符号整数