programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Tim Cooke
• Devaka Cooray
• Ron McLeod
• Jeanne Boyarsky
Sheriffs:
• Liutauras Vilda
• paul wheaton
• Junilu Lacar
Saloon Keepers:
• Tim Moores
• Stephan van Hulst
• Piet Souris
• Carey Brown
• Tim Holloway
Bartenders:
• Martijn Verburg
• Frits Walraven
• Himai Minh

# byte range

Ranch Hand
Posts: 383
• Number of slices to send:
Optional 'thank-you' note:
byte x=64;
byte y=5;
byte z= (byte)(x*y);

What is the value of z? The answer is 64, I am not getting how it is 64. I think if (x*y) goes out of byte range, output will be 0. Please can anyone explain?

Ranch Hand
Posts: 278
• Number of slices to send:
Optional 'thank-you' note:
Answer 64 is correct ,as byte limit is 128 only.
320 is out of limit so
320-128-> 192(of -ve side) again out of limit
so goes to +ve side, 192-128->64 of +ve

Ranch Hand
Posts: 109
• Number of slices to send:
Optional 'thank-you' note:
hi

64 * 5 is 320

320 in binary is 101000000

Since byte cannot accomodate anything greater than 127 it truncates any leftmost bits that is more than 8 bits counting from right

Hence it retains 01000000, and this is equivalent to 64
Hence you get 64

author and cow tipper
Posts: 5006
1
• Number of slices to send:
Optional 'thank-you' note:

Originally posted by dolly shah:
byte x=64;
byte y=5;
byte z= (byte)(x*y);

64 * 5 = 320

The JVM treats the results of multiplications as an int, so as it does the math, it's treating it as an int in memory. So far, no problem.

In Binary, 320 = 101000000, but, a byte can only use 8 of those, so everything after the first eight digits is truncated with the cast, giving you: 01000000

If you then turn 01000000 into decimal, you get 64.

So, that's what's going on under the covers.

Pretty kewl, eh?

-Cameron McKenzie

Cameron Wallace McKenzie
author and cow tipper
Posts: 5006
1
• Number of slices to send:
Optional 'thank-you' note:
Shoot....As I responded, there were no other responses.

You've got to be fast on this board. Just to many people smarter than me trying to help out.

-Cameron McKenzie

Sheriff
Posts: 11343
• Number of slices to send:
Optional 'thank-you' note:

Originally posted by Cameron McKenzie:
Shoot....As I responded, there were no other responses...

That happens to me a lot. Especially when I spend time going back and forth about how much detail to include in my response.

Ranch Hand
Posts: 1274
• Number of slices to send:
Optional 'thank-you' note:
Cats and Mice and Bits:
http://www.javaranch.com/campfire/StoryBits.jsp

Bu.

 You had your fun. Now it's time to go to jail. Thanks for your help tiny ad. the value of filler advertising in 2021 https://coderanch.com/t/730886/filler-advertising
reply
Similar Threads