gpt4 book ai didi

c - 在 long 中找到最重要的设置位

转载 作者:太空宇宙 更新时间:2023-11-04 07:25:16 25 4
gpt4 key购买 nike

我处于一种独特的情况,即搜索“最高有效位”会产生太多 结果,但我找不到符合我需要的答案!

问题本身很简单:“如何找到无符号长整型中的最高有效位?”当我进行计算时,最右边的位位置是位置“0”。

我知道它涉及屏蔽最低位,检查然后向左移动一次同时增加我的计数,然后重复第二个最低位,等等。

我以前做过这个,但不管出于什么原因我现在不能做。


编辑:“最重要的”是指最左边的设置位,如有任何混淆,请见谅!*


下面是我的功能解决方案和一些测试用例:

#include <stdio.h>

int findExponent( unsigned long L ){

int exponent = -1;

unsigned long shift = L;

while( 0 != shift )
exponent++, shift >>=1;

if ( exponent >= 0 )
printf("The most significant bit of L is at position %d\n", exponent);
else{
exponent = 0;
printf("L is zero\n");
}
return exponent;
}


int main(int argc, char** argv){

long check = 8L;

findExponent( check );//2
findExponent( 21421L );//14
findExponent( 0L );//(is zero)
findExponent( 1L );//0
}

最佳答案

"How do I find the most significant bit in an unsigned long?"

您可以向右移动直到最后一个 1 被删除。这一刻,值(value)变成了0。

#include <stdio.h>
int main(void) {
unsigned long x = 3333;
unsigned long y = x;
int p = -1;
while (0 != y)
p++, y >>= 1;
if (p >= 0)
printf("The most significative bit of x is at position %d\n", p);
else
printf("x is zero\n");
}

关于c - 在 long 中找到最重要的设置位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18939998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com