How do you define unsigned int in Java?

Asked 2 years ago, Updated 2 years ago, 122 views

Is there a way to define unsigned int in Java? What does unsigned mean in Java? I'm looking at String.hashcode right now and I want to see the possibility of a 32-bit unsigned int crash here.

java integer unsigned

2022-09-22 15:16

1 Answers

By default, there is no unsigned integer in Java. If you want to get a larger positive integer, you can use long instead of int. But there is no way to exclude negative numbers.
However, starting from Java 8, several methods have been added to address unsigned in either Integer or Long classes

    // Java 8
    int vInt = Integer.parseUnsignedInt("4294967295");
    System.out.println(vInt); // -1
    String sInt = Integer.toUnsignedString(vInt);
    System.out.println(sInt); // 4294967295

    long vLong = Long.parseUnsignedLong("18446744073709551615");
    System.out.println(vLong); // -1
    String sLong = Long.toUnsignedString(vLong);
    System.out.println(sLong); // 18446744073709551615

    // // Guava 18.0
    int vIntGu = UnsignedInts.parseUnsignedInt(UnsignedInteger.MAX_VALUE.toString());
    System.out.println(vIntGu); // -1
    String sIntGu = UnsignedInts.toString(vIntGu);
    System.out.println(sIntGu); // 4294967295

    long vLongGu = UnsignedLongs.parseUnsignedLong("18446744073709551615");
    System.out.println(vLongGu); // -1
    String sLongGu = UnsignedLongs.toString(vLongGu);
    System.out.println(sLongGu); // 18446744073709551615

You can write it like this.


2022-09-22 15:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.