• Post Reply Bookmark Topic Watch Topic
  • New Topic
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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why does Byte do this?

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

I was doing a little test program...multiplying a byte, initialised to 1, by 8. I print out the result after each multiplication.
The results are:
2
4
8
16
32
64
-128
0

Can anyone tell me why the seventh value is -128 (why minus?) and the eighth is 0??
I know the Byte ranges from -128 to 127....I'm guessing that has something to do with it.

Thanks in advance
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Shanna Ripley wrote:Can anyone tell me why the seventh value is -128 (why minus?) and the eighth is 0??
I know the Byte ranges from -128 to 127....I'm guessing that has something to do with it.



Short answer. The number overflowed.

For the longer answer why the numbers are -128 and then zero -- google for "twos complement", which is the format used to represent signed numbers in Java.

Henry
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The top bit is used for the sign. So, when you get to 128, the bit pattern would be
1000 0000

The first bit tells us the answer is negative, then we use 2's complement to figure out the value. When you next double that, you would have

1 0000 0000

but the leading 1 gets chopped off and lost forever, leaving you with 0.
 
Shanna Ripley
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Henry and Fred
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic