• 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
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Out put of program

 
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
why is out put is coming -126,instead of 127 please clearly Expalin .I guess that there is some sign bit effect but don't understand what is it please help me.

Thanks

class Casting {
public static void main(String [] args) {
long l = 130L;
byte b = (byte)l;
System.out.println("The byte is " + b);
}
}
 
Ranch Hand
Posts: 152
VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you're right, the byte primitive in Java is signed (data types).

internally (at byte code level) the JVM converts 'byte' and 'short' primitives to type 'int'.
The effect we are seeing here is called "(integer) overflow" and leads to a model of so-called "circular arithmetic",
in which the greatest positive integer is followed by the smallest negative integer.

Why not change the representation to hexadecimal?



HTH
Matt
 
Ranch Hand
Posts: 96
Eclipse IDE Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Related Ranch Question (RRQ)

Cheers,
Wim
 
Punya Pratap Singh
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot Matt Cartwright,but why to print in hexadecimal ?
Thanks Wim.
 
Matt Cartwright
Ranch Hand
Posts: 152
VI Editor Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
short answer: because it's a byte and not a decimal number, the bits set do count, not its representation in decimal notation
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic