可能重複的位數:
Count the number of set bits in an integer
Best algorithm to count the number of set bits in a 32-bit integer?計數是「上」,在一個字節
這是考試的問題,這是我的全部 - 「伯爵在一個字節中「開」的位的數量是「1」,我假設。我需要創建一個BitArray,隨機填充它,然後遍歷它,或者有不同的方式嗎?
可能重複的位數:
Count the number of set bits in an integer
Best algorithm to count the number of set bits in a 32-bit integer?計數是「上」,在一個字節
這是考試的問題,這是我的全部 - 「伯爵在一個字節中「開」的位的數量是「1」,我假設。我需要創建一個BitArray,隨機填充它,然後遍歷它,或者有不同的方式嗎?
使用BitArray可能是有效的,但你也可以做
byte b = ... ;
int count = Convert.ToString(b,2).ToCharArray().Count(c => c=='1');
我認爲這被稱爲lambda表達式,對吧? BtW,對不起,我不能upvote,我還沒有註冊。 – Max 2011-03-21 19:50:02
yes'c => c =='1''是一個lambda表達式謂詞。 – 2011-03-21 19:53:12
檢出http://en.wikipedia.org/wiki/Hamming_weight – JavaKungFu 2011-03-21 19:37:54