aspose file tools*
The moose likes Beginning Java and the fly likes Operators - confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Operators - confusion" Watch "Operators - confusion" New topic
Author

Operators - confusion

Werner Otto
Greenhorn

Joined: Sep 28, 2003
Posts: 2
Example code:
class L {
public static void main(String s[]) {
int i = 1 | 2 ^ 15 & 7 ^ 13 | 2
System.out.println(i % 5)
Result: 1
Problem: (15 & 7) = 7
(2 ^ 7) = 5
Can someone please explain how to get to these answers, I ran the program and thats fine, but my understanding is little.
mpt@micprotec.co.za
Peter Gal
Greenhorn

Joined: Sep 28, 2003
Posts: 1
i think it works as follows:
- precedence is the same! for all bitwise operators
- associativity right-to-left
so "int i = 1 | 2 ^ 15 & 7 ^ 13 | 2" results in 11:
13 | 2 is 15
15 ^ 7 is 8
8 & 15 is 8
8 ^ 2 is 10
10 | 1 is 11
then 11%5 gives 1
CallMeWhatever Otto
Greenhorn

Joined: Sep 12, 2003
Posts: 3
I think I need to stop you right there.
Firstly how does:
13 | 2 = 15
15 ^ 7 = 8
8 & 15 = 8
8 ^ 2 = 10
10 | 1 = 11
is it perhaps, 13 + 2 where the "|" realy equals a "+"
and 15 - 7 = 8 where the "^" resembles a "-"
and "&" ???
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Think bits!
13 = 1101
When we "or" in a 2 (0010) we set the "2" bit to 1 and get 1111 = 15.

Takes some getting used to, but it can be a lot fun.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1817

CallMeWhatever Otto:
Welcome to JavaRanch!
We don't have many rules here at JavaRanch, but we do have one. Please change your display name to comply with The JavaRanch Naming Policy.
Thanks Pardner! Hope to see you 'round the Ranch!


Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Herb Schildt
Author
Ranch Hand

Joined: Oct 01, 2003
Posts: 239
When applied to integer types (long, int, short, char, and byte) the operators |, &, and ^ act on the individual bits with their operands. Thus, they are called bitwise operators. The bitwise operators cannot be applied to float, double, or to class types. Other bitwise operators are ~, <<, >>, and >>>. These are the one's complement, left shift, right shift, and unsigned right shift, respectively.
In general, the bitwise operators are used to test, set, or shift the individual bits that make up an integer value according to the logical operations that they represent. Thus, an expression such as 7 & 8 is not the same as 7 + 8.


For my latest books on Java, including my Java Programming Cookbook, see HerbSchildt.com
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Operators - confusion