开发者

java integer handling

开发者 https://www.devze.com 2023-03-01 18:50 出处:网络
When I run this program, it outpu开发者_JAVA百科ts -43. public class Main { public static void main(String[] args) {

When I run this program, it outpu开发者_JAVA百科ts -43.

public class Main {
    public static void main(String[] args) {
        int a=053;
        System.out.println(a);
    }
}

Why is this? How did 053 turn into -43?


I've no idea how it's becoming negative, but starting an integer with 0 specifies it's octal (base eight). 53 in base eight is 43 in base ten.


The java tutorials http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

 int decVal = 26;      // The number 26, in decimal
 int octVal = 032;     // The number 26, in octal <<== LOOK FAMILIAR?
 int hexVal = 0x1a;    // The number 26, in hexadecimal
 int binVal = 0b11010; // The number 26, in binary

Yup... it's a gotcha!

Cheers. Keith.


It prints out 43, not -43. That is because if you write a number with a leading 0, it is an octal constant.

From here, http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

int octVal = 032; // The number 26, in octal


As http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.1 says:

An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.

And its format is:

OctalNumeral:
    0 OctalDigits
    0 Underscores OctalDigits

So, if you use

int octVal = 053;

or,

int octVal = 0_53;

both of them, you will get 43.


This from googling 'how to convert octal to decimal'

Octal to Decimal

  1. Start the decimal result at 0.
  2. Remove the most significant octal digit (leftmost) and add it to the result.
  3. If all octal digits have been removed, you're done. Stop.
  4. Otherwise, multiply the result by 8.
  5. Go to step 2.

So 0 + 5 = 5, 5 * 8 = 40, 40 + 3 = 43

0

精彩评论

暂无评论...
验证码 换一张
取 消