bitwise operators for finding less than in c

后端 未结 4 1437
离开以前
离开以前 2020-12-19 03:45

This is a homework assignment which requires me to come up with a function to determine if x < y, if it is I must return 1, using only bitwise o

4条回答
  •  情歌与酒
    2020-12-19 04:27

    I think it can be achived doing following:

    1. Xor both numbers, that will give you bits that differs
    2. Get the most significant bit that differs, as this one will make a difference
    3. Check if that most significant bit belongs to bigger value

    Code:

    int less(int x, int y) {
        //Get only diffed bits
        int msb = x ^ y;
        //Get first msb bit
        msb |= (msb >>  1);
        msb |= (msb >>  2);
        msb |= (msb >>  4);
        msb |= (msb >>  8);
        msb |= (msb >> 16);
        msb = msb - (msb >> 1);
        //check if msb belongs to y;
        return !((y & msb) ^ msb);
    }
    

提交回复
热议问题