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

來源:互聯網
上載者:User

Write code to implement the following function:

/*

 *Generate mask indicating leftmost 1 in x.  Assume w=32.

 *For example 0xFF00 -> 0x8000, and 0x6600 -> 0x4000.

 * If x = 0, then return 0.

*/

int leftmost_one(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 15 arithmetic, bit-wise, and logical operations.

 Hint: Fisrt transform x into a bit vector of the form[0...011...1].

int leftmost_one(unsigned x){    unsigned tmp;    //構造從原始x最高位往右所有位都為1的無符號數    tmp = x >> 1;    x |= tmp;    tmp = x >> 2;    x |= tmp;    tmp = x >> 4;    x |= tmp;    tmp = x >> 8;    x |= tmp;    tmp = x >> 16;    x |= tmp;    unsigned y,z;    y = x + 1;    z = y;    y >>= 1;    //倘若原始x最高位為31位    z == 0 && (y = 0x8000);    return y;}

分析:
題目要求:為數A(0101)產生一個掩碼M,A&M結果只保留A中最高位的1,即(0100)。所以(0100)就是A的掩碼。

原理:若A為(0101 0101),若能得到B(0111 1111),則B+1得到C(1000 0000),然後C右移一位就可得到要求的掩碼M(0100 0000)。

那麼關鍵就是得到上述的B,若A為(0101 0101)(假設從右數第n位為最高位1):

           A  |  (A >> 1)  ---> B1(011* ****)  , 不管*代表0還是1,現在可得到第n,n-1位為1的數B1。

          B1 |  (B1>>2) --->B2(0111 1***),不管*代表0還是1, 現在可得到第n,n-1,n-2,n-3位為1的數B2.

          B2 | (B2>>4) ---->B3(0111 1111) , 此時,可得到B

顯然,若A共w位,按上述過程,當Bi | (Bi>>w/2)一定可以得到B
有一個特殊情況,若A的最高位1恰好在w-1位上,得到的B就是(11......11)全1,這時候B+1得到C(00......00)全0,此時就用到

代碼中

 z == 0 && (y = 0x8000),

即特殊情況下直接返回0x8000

 

聯繫我們

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