May be I am too tired.
Why dont’t the following display the same value?
int x = 42405;
System.out.println(x << 8);
System.out.println((x &0x00ff) << 8);
The lower bits should be clear in both cases
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
EDIT: Okay, I’m leaving the bottom part for posterity…
If
xisint, then it’s pretty simple:x << 8will have the same value asx & 0xffif and only if none of the “middle” 16 bits are set:xwill be rendered irrelevant by the left shiftxare preserved by the maskingIf there are any of the “middle” 16 bits set, then
x & 0xffwill differ fromxin a bit which is still preserved by the shift, therefore the results will be different.I don’t understand why you’d expect them to always give the same results…
I’m going to assume that the type of
xisbyte, and that it’s actually negative.There’s no shift operation defined for
byte, so first there’s a transformation toint… and that’s what can change depending on whether or not you’ve got the mask.So let’s take the case where
xis -1. Then(int) xis also -1 – i.e. the bit pattern is all 1s. Shift that left by 8 bits and you end up with a bit pattern of 24 1s followed by 8 0s:Now consider the second line of code – that’s taking
x & 0xff, which will only take the bottom 8 bits of the promoted value ofx– i.e. 255. You shift that left by 8 bits and you end up with 16 0s, 8 1s, then 8 0s: