// counting_bits: x86 (32-bit) embedded assembly to count number of set bits extern "C" int bits_set(int value); __asm__( "_bits_set:\n" " mov %ecx, %ebx\n" " mov $0, %ecx\n" // ecx: bit counter "check_zero:\n" " cmp $0, %ebx\n" // done? (that is, no more bits) " je done\n" " mov %ebx, %edx\n" // lsb of %ebx is set? " and $0x01, %edx\n" " jz lsb_is_zero\n" " add $1, %ecx\n" // if so, count it "lsb_is_zero:\n" " shr $1, %ebx\n" // shift off the bit just counted " jmp check_zero\n" // try next bit "done:\n" " mov %ecx, %eax\n" " ret\n" ); #include using namespace std; int main() { cout << "Enter a number: "; int num; cin >> num; int number_of_bits_set = bits_set(num); cout << num << " has " << number_of_bits_set << " bits set" << endl; return 0; }