Henrique Boreg

Greenhorn

Posts: 23

posted 11 years ago

Hello, I was looking over the Rectangle2D class in java.awt.geom, and I came across a method that given an (x,y) point, returns its relative position to the rectangle (eg. left, right, bottom or top). Pretty much, the whole method is:

my question is, what exactly is going on in the assignments such as out |= OUT_TOP | OUT_BOTTOM ??

ps. OUT_LEFT = 1, OUT_TOP = 2, OUT_RIGHT = 4, OUT_BOTTOM = 8

Thanks.

my question is, what exactly is going on in the assignments such as out |= OUT_TOP | OUT_BOTTOM ??

ps. OUT_LEFT = 1, OUT_TOP = 2, OUT_RIGHT = 4, OUT_BOTTOM = 8

Thanks.

"I wrote an all-Java OS in 1998 but can't be sure if or how it works... it's still booting"

posted 11 years ago

1, 2, 4, and 8 are all integers with a single bit set -- binary 0001, 0010, 0100, and 1000, respectively. The "|" operator is the bitwise "or" operation, which returns a value that has 1-bits in every location that is a 1 in either of its operands. Because those constants each have a single "1" bit in them, you can use a single int to represent a set of them -- i.e., OUT_TOP | OUT_LEFT means 1010, and you can recover each of the constituent parts separately. Given a point that's above and to the left of the rectangle, this routine will return OUT_TOP | OUT_LEFT or binary 0011, or 3 decimal. You can then say

"&" is bitwise "and", and its result has a 1 bit only in those locations where both arguments have a "1".

"&" is bitwise "and", and its result has a 1 bit only in those locations where both arguments have a "1".