1 2 3 Previous Next 31 Replies Latest reply: Jul 26, 2007 12:00 PM by 807605

# How do Bitwise Operators work?

Hi everybody

I know a little bit of bitwise operators and I am getting some problems working with them.

For example, imagine the byte 0x42 (Or 01000010). Now I want to build a long having this byte on the first position starting from the left so I try the following code:
``long l = 0x42 << 56;``
However, this operation seems to work like if I have written:
``long l = 0x42 << 24``
That is, the new long is a String of only 32 bits. Why does this command ignore the first 32 bits? Any ideas?
• ###### 1. Re: How do Bitwise Operators work?
``long l = 0x42L << 56;``
• ###### 2. Re: How do Bitwise Operators work?
It works! Thanks a lot!
• ###### 3. Re: How do Bitwise Operators work?
> It works!

Do you understand why?

~
• ###### 4. Re: How do Bitwise Operators work?
Not at all. Can you explain it?
• ###### 5. Re: How do Bitwise Operators work?
The reason, by the way, is that the expression 0x42 << 56 has type int --
its assignment to a long variable doesn't influence an expression's type.
• ###### 6. Re: How do Bitwise Operators work?
Ok. Now I understand it. Thank you very much for your help.
• ###### 7. Re: How do Bitwise Operators work?
On a small tangent, I asked this question yesterday: what does this program output?
Guess, then copy and run to see if you were right.
``````public class PartyPretzel {
public static void main(String[] args) {
System.out.println(12345 + 5432ll);
}
}``````
• ###### 8. Re: How do Bitwise Operators work?
> On a small tangent, I asked this question yesterday:
what does this program output?

Grooooooooovy.

~
• ###### 9. Re: How do Bitwise Operators work?
> On a small tangent, I asked this question yesterday:
what does this program output?
Guess, then copy and run to see if you were right.
``````public class PartyPretzel {
public static void main(String[] args) {
System.out.println(12345 + 5432ll);
}
}``````

Wauu. I would have bet my hand saying that the result will be 66666 and it is 17777. And the reason for this is....
• ###### 10. Re: How do Bitwise Operators work?
> On a small tangent, I asked this question
yesterday:
what does this program output?

Grooooooooovy.
A haunted JVM?
• ###### 11. Re: How do Bitwise Operators work?
> And the reason for this is....

Lack of attention to detail? ;o)

@BDLH: How do you get the code tags not to screw that up?

~
• ###### 12. Re: How do Bitwise Operators work?
I would say because the numbers are greater than the maximum integer value. Am I right?
• ###### 13. Re: How do Bitwise Operators work?
Or at least one of them
• ###### 14. Re: How do Bitwise Operators work?
I would say because the numbers are greater than the
maximum integer value. Am I right?
Nope. 66666 is not that big, is it? Integer.MAX_VALUE is 2147483647
1 2 3 Previous Next