-1

When I went through numerous websites before posting this question on bit masking all i understood was it's used to toggle switch between 1's and 0's and usually used in pixel based graphic project. Now as a beginner really didn't understand why do we toggle the switch and how it is used in graphics.. Also why do we use bit masking to extract the bits??

shet_tayyy
  • 5,366
  • 11
  • 44
  • 82
  • 1
    Why is this tagged with three different languages, when you only seem to be talking about Java? Rules for sign-extension and bit-shifting cannot be expected to be the same across a random set of programming languages ... โ€“ unwind Jun 16 '14 at 08:23

1 Answers1

3

The answer lies in the JLS. Section 5.6.2:

Widening primitive conversion (ยง5.1.2) is applied to convert either or both operands as specified by the following rules:

  • If either operand is of type double, the other is converted to double.
  • Otherwise,if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.

The last point is of interest. This means that both b is converted to int before the shift operation is carried out.

Thus, b, which used to be 0xF1, is promoted to 0xFFFF FFF1.

Then the shift is performed:

0xFFFF FFF1 >>> 4 == 0x0FFF FFFF

Then casted to byte:

(byte) 0x0FFF FFFF == 0xFF

And you get b == -1.


e is 15 because of the mask.

First, b is promoted from 0xF1 to 0xFFFF FFF1.

Then it is ANDed with 0xFF:

0xFFFF FFF1 & 0x0000 00FF == 0x0000 00F1

Then it is shifted right 4 bits:

0x0000 00F1 >> 4 == 0x0000 000F

Then it is casted to byte:

(byte) 0x0000 000F == 0x0F

And you get e == 15

Edit: Didn't hit "F" enough times, ended up with 16-bit ints... Hopefully fixed, thanks @Stefan!

Community
  • 1
  • 1
awksp
  • 11,764
  • 4
  • 37
  • 44