James Carter
James Carter

Reputation: 387

Bitwise operators - precision

Three questions that I seem to be stuck on:

  1. Why is the code x & ~077 better than this line of code x & 0177700. Would it be because there is less loss of precision?

  2. Why is this code incorrect for setting bit 5 in a number? num = num + 0x20 Would it be because we need to use logical or, |, not the +?

  3. Why is this code x & 0xFF better than this line of code (x << 24) >> 24? The right expression could result in sign extension which changes the original int. I am sure that is correct from examples I have done.

Upvotes: 1

Views: 271

Answers (1)

Emanuele Paolini
Emanuele Paolini

Reputation: 10172

1, why is this code x & ~077 better than this line of code x & 0177700.

Because in the second one you are making assumptions on the length of the integer type of x

2, why is this code incorrect for setting bit 5 in a number? num = num + 0x20 Would it be because we need to use logical or, |, not the +?

yes! they are different operators.

Upvotes: 1

Related Questions