Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Operators - confusion

 
Werner Otto
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Herb Schildt
Author
Ranch Hand
Posts: 253
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic