> For the complete documentation index, see [llms.txt](https://valineliu.gitbook.io/deuterium-wiki/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://valineliu.gitbook.io/deuterium-wiki/reading/cs-jing-dian-shu-ji/csapp-3e-homework-solution/2.-representing-and-manipulating-information/2.65-odd-ones.md).

# 2.65 Odd Ones

★★★★

**Problem**:

Write code to implement the following function:

```c
/* Return 1 when x contains an odd number of 1s; 0 otherwise. Assume w=32 */
int odd_ones(unsigned x);
```

Your function should contain a total of at most 12 arithmetic, bitwise, and logical operations.

code：

```c
#include <stdio.h>
#include <assert.h>

int odd_ones(unsigned x) {
    x ^= x >> 16;
    x ^= x >> 8;
    x ^= x >> 4;
    x ^= x >> 2;
    x ^= x >> 1;
    return x & 0x1;
}

int main() {
    unsigned uval = 0x10101010;
    assert(!odd_ones(uval));
    uval = 0x10101011;
    assert(odd_ones(uval));
    return 0;
}
```
