Re: [問題] 計算數字的二進制長度
※ 引述《chrisjon (與程式最後的決戰)》之銘言:
: 請問有直接計算二進制長度的語法嗎?
: 例如:12(10) = 1100(2)
: 那長度就是 4
: 我是有想說寫a|(2^31-1),然後再&1計算1有幾個就是它的長度
: 不過,是否有直接的語法可以用呢?
沒有特別去想有沒有特殊解法, 直觀的做法就是最左邊的1出現的位置
#include <stdio.h>
int Blen(int a)
{
int i,b;
for (i=31,b=0x80000000;i>=0 && !(a&b);i--,b>>=1)
;
return(i+1);
}
int main(void)
{
printf("%d\n",Blen(12));
return(0);
}
Bleed
--
World of bleed1979
http://bleed1979.myweb.hinet.net/
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.130.143.186
討論串 (同標題文章)
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章