CSAPP(1):數位電腦表示——課後題

來源:互聯網
上載者:User

標籤:

2.65

int even_ones(unsigned x)

要求:return 1 when x contains an even number of 1s; 0 otherwise. 假設int 有 w=32位。

分析:最應該使用的是迴圈,但是迴圈語句不能使用。如果一個一個的寫成語句,需要32次;這裡使用二分法,那麼操作就變成了Log232 =5次。二分法蘊含了迴圈同時簡化了迴圈遍曆。如何使用二分法?

  題目是判斷x中1的奇偶數,可以將x一分為2,前16位x1與後16位x2,x3=x1^x2,則,如果x有偶數個1,x3必定有偶數個1;如果x有奇數個1,x3必定有奇數個。

int even_ones(unsigned x){     x ^= (x >> 16);     x ^= (x >> 8);     x ^= (x >> 4);     x ^= (x >> 2);     x ^= (x >> 1);     return !(x & 1);    }

 

2.66

int leftmost_one(unsigned x)

要求: generate mask indicating leftmost 1 in x. assume w=32; if x=0, then return 0;

提示:先將x轉換成形如[0..011..1]的位向量

分析:這裡就是尋找最高位的1在位向量x中是第幾位,應該使用迴圈,然後迴圈不能用,這裡使用二分法。首先,如【提示】中,先將x轉換成形如[0..011..1]的位向量,即:最高位1之後的所有位都變為1。

int leftmost_one(unsigned x){     x |= x >> 1;     x |= x >> 2;     x |= x >> 4;     x |= x >> 8;     x |= x >> 16;     x &= ~(x >> 1);     return x;}

CSAPP(1):數位電腦表示——課後題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.