Is Java int always 32 bits?

Will Java int always and everywhere be a 32-bit signed integer?

+61
java
Jun 23 '09 at 14:40
source share
4 answers

Yes, it is defined in the Java Language Specification .

From Section 4.2: Primitive Types and Values :

The integral types byte , short , int and long , whose values ​​are 8-bit, 16-bit, 32-bit, and 64-bit subscription are integers with two additions, respectively, and char , whose values ​​are 16-bit unsigned integers representing UTF-16 code units (Β§3.1).

In addition, from Section 4.2.1: Integral Types and Values :

Values ​​of integral types are integers in the following ranges:

  • For bytes from -128 to 127 inclusive
  • In short, from -32768 to 32767 inclusive
  • For int, from -2147483648 to 2147483647, inclusive
  • Long time from -9223372036854775808 to 9223372036854775807 inclusive
  • For char, from '\ u0000' to '\ uffff' inclusive, i.e. from 0 to 65535
+100
Jun 23 '09 at 14:41
source share

int - 32 bits. If you need more, long is 64 bits.

+7
Jun 23 '09 at 14:45
source share

As an option, if the length of 64 bits does not meet your requirement, try java.math.BigInteger .

This is suitable for situations where the number does not exceed 64 bits.

 public static void main(String args[]){ String max_long = "9223372036854775807"; String min_long = "-9223372036854775808"; BigInteger b1 = new BigInteger(max_long); BigInteger b2 = new BigInteger(min_long); BigInteger sum = b1.add(b1); BigInteger difference = b2.subtract(b1); BigInteger product = b1.multiply(b2); BigInteger quotient = b1.divide(b1); System.out.println("The sum is: " + sum); System.out.println("The difference is: " + difference); System.out.println("The product is: " + product); System.out.println("The quotient is: " + quotient); } 

Output:

Amount: 18446744073709551614

The difference is as follows: -18446744073709551615

Product: -85070591730234615856620279821087277056

Ratio: 1

+2
Jul 04 '16 at 1:34
source share

Java 8 has added some unsigned integer support. The int primitive is still signed, however some methods will interpret them as unsigned.

The following methods have been added to the Integer class in Java 8:

  • compareUnsigned (int x, int y)
  • divideUnsigned (int divend, int divisor)
  • parseUnsignedInt (String s)
  • parseUnsignedInt (String s, int radix)
  • Unsigned (int divend, int divisor)
  • toUnsignedLong (int x)
  • toUnsignedString (int i)
  • toUnsignedString (int i, int radix)

Here is a usage example:

 public static void main(String[] args) { int uint = Integer.parseUnsignedInt("4294967295"); System.out.println(uint); // -1 System.out.println(Integer.toUnsignedString(uint)); // 4294967295 } 
0
Feb 17 '16 at 20:31
source share



All Articles