Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

byte question

Status
Not open for further replies.

satellite03

IS-IT--Management
Dec 26, 2003
248
IN
hi, i am testing this code
Code:
byte x =64,y;
y = (byte)(x<<2);
System.out.println(y);
output is 0. why?

but, if i test
Code:
byte x =64,y;
y = (byte)(x<<1);
System.out.println(y);
its giving -128 . why ?

i know byte has range max=127 and min = -128 .

but using this two, i find the above two results are contradictory. both the cases results are out of range...but they are printing different results. why?
 
hi, sedj, thanks for the link. i am aware of the shift operators.

if i want to get the number after shifting, then quick rule is multiply the number by 2^number_of_shifts(for left shift).

so applying this quick rule in my first code

64*2^2 = 256

and in second code,64*2^1 = 128

both of them are out of byte max range 127. is not it?

but while printing, they did not print it, rather they printed different output.
so why they gave output differently , why not the same?



you know, i was expecting -128( which is min value of byte ), bcoz i thought, if it is out of range then it will go back reverse way to -128 and onwards.


i also thought,the output to be the highest value(i.e 127) if it goes out of range....but it is not.

however, those two code printed two different output although both of them are out of range as i have shown.

 
Well in binary 64 is 01000000 and if you shift once then you have 10000000 which acting as a signed number (last bit is the signed bit) then you have -128 by the 2's complement. If you shift twice then you get 00000000 as it does not carry which is obviously 0. You would have to perform an arithmetic operation for overflow to come into effect. Hope that helps.

-JavaDude32
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top