• Post Reply Bookmark Topic Watch Topic
  • New Topic

binary literal  RSS feed

 
meeta gaur
Ranch Hand
Posts: 305
Notepad Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
byte data1 = (byte)0b1100110011; //it accepts only 7 bits 0110011=51
System.out.println(data1);
51

byte data2 = (byte)0b10101010; //0101010
System.out.println(data2);
-86

why ? it should be 42
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
meeta gaur wrote:why ? it should be 42

10101010base-2 is 42? On what planet?

Winston
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
meeta gaur wrote:byte data1 = (byte)0b1100110011; //it accepts only 7 bits 0110011=51
System.out.println(data1);
51

It takes the lower 8 bits, because a byte is 8 bits. You do a cast, so the higher bits are discarded.

meeta gaur wrote:byte data2 = (byte)0b10101010; //0101010
System.out.println(data2);
-86

why ? it should be 42

No. A byte is an 8-bit integer, stored in two's complement format, in which 0b10101010 is equal to -86.
 
meeta gaur
Ranch Hand
Posts: 305
Notepad Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper de Jong wrote: . . . You do a cast, so the higher bits are discarded. . . .
By higher, you mean bits 8‑31 inclusive. 0b10101010 is an int, with 32 bits. As Jesper has said, the topmost 24 0s are removed by the cast, leaving -86.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!