深入理解電腦系統第二版課後習題2.65

來源:互聯網
上載者:User

Write code to implement the following functions:

 /*Return 1 when x contains an odd number of 1s; 0 otherwise.

   Assume w = 32. */

int odd_ones(unsigned x);

Your function should follow the bit-level integer coding rules(page 120),except that you may assume that data type int has w = 32 bits.

       Your code should contain a total of at most 12 arithmetic, bit-wise, and logical operations.

解答:

用到的主要原理:1.       1^1 = 1       0^0 = 0       1^0 = 1        0^1=1

                                2.        奇數 - 偶數 = 奇數,偶數 - 偶數 = 偶數

,對於unsigned x,高16位與低16位異或,因為1^1 = 0,得到的16bit中含1的個數恰好是x中1的個數減去偶數個。以此類推,最後異或後得到一位,如果是1,就說明x含奇數個1,若是0,則說明x含偶數個1。

編寫代碼是為了減少操作,用x的一部分儲存b。

int odd_ones(unsigned x){    //用x的低16位表示b,x ^ a 對應 b ^ a    unsigned a = x >> 16;    x = x ^ a;         //用x的低8位表示b    a = x >> 8;    x = x ^ a;        //用x的低4位表示b    a = x >> 4;    x = x ^ a;        //用x的低2位表示b    a = x >> 2;    x = x ^ a;        //用x的低1位表示b    a = x >> 1;    x = x ^ a;        //此時,x的最低1位即最後的結果    return  x & 0x1;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.