Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a 32bit integer in java?

I'm looking at an app in java that runs on both 32bit and 64bit systems, and it deals mainly with IP addresses. These IP addresses are kept as integers, and the normal type for this wastes a ton of memory on 64bit platforms (and yes, memory use has already been shown to be an issue here). How do you declare 32bit integral values that stay at 32bits even on x64 architectures?

As I'm a java novice, if there's a built-in type that's already designed to handle IP addresses please feel free to point that out to me ;)

like image 542
Joel Coehoorn Avatar asked Oct 31 '10 23:10

Joel Coehoorn


People also ask

How do you create a 32-bit integer in Java?

int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1.

How do you create a 32-bit integer?

You can declare 8-, 16-, 32-, or 64-bit integer variables by using the __intN type specifier, where N is 8, 16, 32, or 64. The types __int8 , __int16 , and __int32 are synonyms for the ANSI types that have the same size, and are useful for writing portable code that behaves identically across multiple platforms.

Can a'int be of 32 bits?

In 32-bit operating systems, the int type is usually 32 bits, or 4 bytes. Thus, the int type is equivalent to either the short int or the long int type, and the unsigned int type is equivalent to either the unsigned short or the unsigned long type, depending on the target environment.

Is Java int always 32-bit?

Yes, a Java int is 32 bits in all JVMs and on all platforms, but this is only a language specification requirement for the programmer-perceivable width of this data type.


1 Answers

Java has specific widths for its data types, for portability. Integers are 32 bits wide even on 64-bit platforms. The Java language specification states quite clearly (slightly paraphrased to make more readable, in my opinion):

The integral types are byte, short, int, and long, whose values are respectively 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, and char, whose values are 16-bit unsigned integers representing UTF-16 code units.

This is arguably due to the many portability issues discovered in C with the different widths (and even encodings like two's complement, ones' complement and sign/magnitude) of integers that Java hoped to avoid, especially since it was meant to run on as many different platforms as possible.

As to a built-in type for handling IP addresses, Java has both Inet4Address and Inet6Address, depending on your needs (and their common ancestor, InetAddress).

like image 101
paxdiablo Avatar answered Oct 03 '22 09:10

paxdiablo