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