Home > Software engineering >  A C function int firstBitEqualsLast(int x) which returns 1 if bit_0 equals bit_31 and returns 0 othe
A C function int firstBitEqualsLast(int x) which returns 1 if bit_0 equals bit_31 and returns 0 othe

Time:01-25

Legal operators ! ~ & ^ | << >>

I have tried this code:

int lhs = ((x << 31)>>31);
int rhs = (x >> 31);
return (~(lhs ^ rhs));

But output was not always as expected

CodePudding user response:

  1. I don't know of any data type whose MSB is bit 30. However, 32- bit ints have their MSB in bit 31, so you might try using that value instead.

  2. You should always use unsigned types when performing bit operations.

    #include <stdint.h>
    
    uint32_t lsb = ((uint32_t)(value & 1));
    uint32_t msb = ((uint32_t)((value >> 31) & 1));
    
    return !(msb ^ lsb);
    
  • Related