user3573388
user3573388

Reputation: 191

What does "(a << 24 | b << 16 | c << 8 | d)" mean?

 public int getRGB(Object inData) {
     return (getAlpha(inData) << 24)
         | (getRed(inData) << 16)
         | (getGreen(inData) << 8)
         | (getBlue(inData) << 0);

 }

So, what does this return statement actually do? Four ints are shifted, but what is returned?

Upvotes: 0

Views: 627

Answers (3)

Laszlo Fuleki
Laszlo Fuleki

Reputation: 342

What you get is the following :

Alpha | Red | Green | Blue - an 32 bit ARGB value - 8 bits for each. As you can see, alpha is shifted 24 bits to the left (leftmost - most significant bits), after which comes the red, with 8 bits, thus placing red in second first 8 bits and masking the remaining 16. Afterward, green is shifted with 8 bits, masking the last byte and finally, blue is put in its place.

Upvotes: 4

Zyl
Zyl

Reputation: 3310

| is bitwise OR with strict evaluation, in contrast to ||, which may stop evaluation of the statements in the condition as soon as one expression returns true. But these methods (presumably) return integers, so in Java you (to my knowledge) cannot test these against true directly anyway. No problem since that is not what you are doing - you are shifting the individual results from the methods, filling up new bits with 0 and cutting off the old ones. What this achieves is to pack the (presumably) at most byte-sized, positive values (0 to 255) in one of the 4 bytes which make up an integer. Essentially this is packing 4 pieces of information which require one byte each into one variable of type integer. The type of the target variable could be anything, as long as it has enough bytes to store the information, but it gets more sloppy and questionable from there.

Upvotes: 0

Eran
Eran

Reputation: 394086

It returns an int whose first (MSB) byte is the Alpha value, its 2nd byte is the Red value, its 3rd byte is the Green value and its last byte is the Blue value.

 highest                              lowest
   bit                                 bit
    |--------|--------|--------|--------|
      Alpha     Red      Green    Blue
     (8 bits) (8 bits) (8 bits) (8 bits)

Upvotes: 9

Related Questions