2016-09-24 212 views
-2

如何迭代C++中的二進制數?錯誤:對二進制轉換無效的操作數(bitset <8>和int)

在提到的功能我得到

invalid operands to binary conversion (bitset<8> and int)

這是在我的代碼的功能,這是越來越既定錯誤

int value(int x) 
{ 
    int temp=0,counter=0; 
    bitset<8> i(x); 
    while (i != 0) { 
     temp = i % 10; 
     if(temp == 1) { 
      counter++; 
     } 
     i = i/10; 
    } 
    return counter; 
} 
+0

X是它的二進制值,我需要的數量,然後從二進制數我應該找到那個號碼的號碼。 –

+1

你真的沒有在這裏使用bitset。你的代碼試圖迭代十進制而不是二進制數。 – iksemyonov

+1

如果你想計數位,你有['bitset :: count()'](http://en.cppreference.com/w/cpp/utility/bitset/count)。 –

回答

3

要計算前8 1點的數量x的位:

int value(int x) 
{ 
    return bitset<8>(x).count(); 
} 

要計算所有的位:

int value(int x) 
{ 
    return bitset<sizeof(x) * CHAR_BIT>(x).count(); 
} 

如果你必須使用一個循環的解決方案:(適應於可用功能解決方案)

int value(int x) 
{ 
    int counter=0; 
    bitset<8> i(x); 
    while (i != 0) { 
     if(i[0] == 1) { 
      counter++; 
     } 
     i >>= 1; 
    } 
    return counter; 
} 
+0

@ Jarod42:只要轉換沒有溢出,就沒有任何特定的實現。你是對的,這樣更好,但在答案上我更願意堅持OP的簽名。 – Dani

+0

嘿@Dani,我在我的程序中實現了你的代碼,唯一的問題是所有的數字都是1的二進制數字,比如2,8我得到的答案是垃圾值,比如14343434. –

+0

@SanjayJain:I測試了所有的變體,他們都工作。你能展示你的整個代碼嗎? – Dani

相關問題