yehwang
yehwang

Reputation: 1

Trying to perform bitwise operation on a negative number to make 0s in bits 31-16 (32 bit number) in C

I have a number, -3, that I would like to use as a 16 bit integer and use an | (or) operator with a 32 bit integer. So ideally, I need it so that -3, in binary two's complement, will be 0000 0000 0000 0000 1111 1111 1111 1101 I've tried bit wise operation using

int x = -3;
x = x << 16;
x = x >> 16;

I thought this would ideally put 0's in the bits 31-16 (0 indexed), but it doesn't seem to work. Any help to achieve this would be appreciated.

Upvotes: 0

Views: 145

Answers (2)

Eric Postpischil
Eric Postpischil

Reputation: 223633

Two ways to get the two’s complement of 3 in 16 bits, with higher bits clear, are:

  • Include <stdint.h> and use (uint16_t) -3.
  • Use -3u & 0xffffu.

Upvotes: 2

chux
chux

Reputation: 154075

Shifting a negative value to the left is undefined behavior.

int x = -3;
x = x << 16; // UB!

Shifting a negative value to the right is implementation-defined behavior.


Best to use unsigned type (or small postive values) when shifting.


to perform bitwise operation on a negative number to make 0s in bits 31-16 (32 bit number) i

Use & to mask and retain only the least significant 16 bits.

int32_t x = -3;
x &= 0xFFFF;

Upvotes: 0

Related Questions