0

I am trying to declare an integer in bytes. What i mean is : i am trying to declare int a = 4 as int a = 0100(i have shortened it here to 4 bits for simplicity. ) Following is the code which i have used and is giving me unexpected output.

public class class4A_d {
public static void main(String[] args) {
    System.out.println("Hello world,this is the main function ");
    int q1=  00000100;  //8 bits 
    int q2 = 00000000000000000000000000000100; //32 bits
    System.out.println("q1 and q2 are respectively "+ q1 + ":" + q2); //q1= 64,q2 =64 
                                       }
                       }

I know java stores integers as 32 bits number in 2,s complement in the back end with weight of each bit progressing in the following manner: 2(^0),2(^1),2(^2).....etc. But here it seems that the weights are in the following manner : 8(^0),8(^1),8(^2).....etc. Can anyone explain this ?

warrior_monk
  • 383
  • 2
  • 14
  • Possible duplicate of [In Java, can I define an integer constant in binary format?](http://stackoverflow.com/questions/867365/in-java-can-i-define-an-integer-constant-in-binary-format) – Marged Apr 17 '17 at 08:33
  • @Marged ..I had previously seen the link that you have mentioned,it does not answer my question mate. – warrior_monk Apr 17 '17 at 08:35
  • Your bit constant is just wrong – Marged Apr 17 '17 at 08:36

1 Answers1

2

When you declare an int, you have the possibility to do it decimal, octal, hexadecimal and binary.

Binary:
Binary int constants begin with 0b, e.g.

int binary = 0b00000100; //decimal: 4

Octal:
Octal int constants begin with 0, so be careful because it can happen, that you use them accidentally, e.g.

int octal = 0127; //decimal 87

Hexadecimal: Hexadecimal int constants begin with 0x, e.g.

int hex = 0xFF; //decimal 255
Alexander Daum
  • 741
  • 4
  • 14