int a=012;
int b=13;
System.out.println(a+b);
The result of the print is 23, so one of them must have been declared in another base format. Which one is this and why?
int a=012;
int b=13;
System.out.println(a+b);
The result of the print is 23, so one of them must have been declared in another base format. Which one is this and why?
That's because your variable a is in base-8 , so a is 0*8^2+1*8^1+2*8^0 (^ means power) , so a=10 in decimal base and that's why your answer is 23.
If you want it to be in base 10 just delete the 0 in a=012
.
Well, you can easily test it whats the base 10 of that number by simply:
System.out.println(Integer.toString(a,10)); // print in the console
All the rest is explained well by E. Armand, ie. how to convert base8 number to base10.
int a = 012; // first '0' means that this number is octal (=10 in decimal)
int b = 13;
System.out.println(a+b); // 012 + 13 = 10 + 13 = 23.
To change output, do use Integer.toString(int i, int radix)
:
System.out.println("binary: 0b" + Integer.toString(a + b, 2)); // binary: 0b10111
System.out.println("octal: 0" + Integer.toString(a + b, 8)); // octal: 027
System.out.println("dec: " + Integer.toString(a + b, 10)); // dec: 23
System.out.println("hex: 0x" + Integer.toString(a + b, 16)); // hex: 0x17