Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - Java does not provide unsigned integer types? thank you
Java does not provide unsigned integer types? thank you
Yes, not provided;

-

What about unsigned types in Java?

In languages like C and C++, there are integer types with different lengths: char, short, int, long (in fact, char is not a real integer, but you can use it as an integer. In practical application scenarios, many people use char to store smaller integers in C language. On most 32-bit operating systems, these types correspond to 1 byte, 2 bytes, 4 bytes and 8 bytes respectively. However, it should be noted that the byte lengths corresponding to these integer types are different on different platforms. Relatively speaking, because Java is designed for cross-platform, no matter what platform it runs on, the bytes in Java are always 1 byte, short is 2 bytes, int is 4 bytes, and long is 8 bytes.

Integers in C language all provide corresponding unsigned versions, but Java does not have this feature. Java doesn't support unsigned types. I feel really uncomfortable. Think about it, many hardware interfaces, network protocols and file formats will use unsigned types! (The types of char provided in Java are different from those in C. chat in Java uses 2 bytes to represent Unicode values, and char in C uses 1 bytes to represent ASCII values. Although char can be used as an unsigned short integer in Java, it is used to represent integers from 0 to 2 16. But it may cause all kinds of weird things, for example, when you want to print this value, you are actually printing the characters corresponding to this value, not the string representation of this value itself).

So, how to deal with the lack of unsigned types in Java?

You may not like the plan I gave you. ...

The answer is: use a signed type that is larger than the unsigned type you want to use.

For example, using short to handle unsigned bytes, using long to handle unsigned integers, and so on. (You can even use char to handle unsigned short integers.). Indeed, it seems wasteful, because you use twice the storage space, but there is no better way. In addition, it should be reminded that accessing long variables is not an atomic operation, so if you are in a multithreaded scene, you have to deal with the synchronization problem yourself.

Address: blogs.com/yuanyq/p/java_unsigned_types.html.

Original address:/player/javaandunsignedtypes.html

By Sean R. Owens