Pregunta

Do you know if there is any rule statement to follow regarding the feasible arithmetic operations among different representations? For instance:7

int a = 0342342;
int b = 0x1abcdef; 
int c = a +b;
System.out.println("It prints out : "+c);

It prints out : 28152529 .

The results (c) is a decimal representation of the addition of the 2 operands a and b.

What if I wanted the result in a particular representation format different from the decimal format?

¿Fue útil?

Solución 2

to print in hex do like this

System.out.printf("It prints out %x\n", c); 

Otros consejos

The numbers 0342342 and 0x1abcdef are literal representations of integers that Java supports for the convenience of developers. Within Java, there really is only one representation of that integer and it is stored in the int type with no reference to a number base (like octal or hexadecimal).

By default, when you print an int, it is displayed in the decimal format.

If you want some other format, you should use System.out.printf:

System.out.printf("Decimal: %d",c);
System.out.printf("Octal: %o",c);
System.out.printf("Hexadecimal: %x",c);

You can use System.out.format in order to represent in different format.

You can find more detailed answer in here: http://docs.oracle.com/javase/tutorial/essential/io/formatting.html

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top