After bigint value exceeds the range, it becomes a negative number when parsed by Java

Note:
This topic has been translated from a Chinese forum by GPT and might contain errors.

Original topic: bigint值超出范围后,java解析后变成负数

| username: TiDBer_0Rc1Ypm9

For example, if the id value is: 16140901070782684196, and it is still negative after using java to parse column.getUint64Value(), how can this situation be resolved?

| username: Billmay表妹 | Original post link

In Java, the range of the long type is -2^63 to 2^63-1. If a value outside this range is converted to a long type, it will cause an overflow and result in an incorrect value. In TiDB, the range of the bigint type is -2^63 to 2^63-1. If a bigint value outside this range is converted to a long type, it will also cause an overflow and result in an incorrect value.

To solve this problem, you can use the BigInteger type to represent bigint values. The BigInteger type can represent integers of any size, avoiding overflow issues. In Java, you can use the new BigInteger(String val) method to convert a string to a BigInteger type, then use the toString() method to convert the BigInteger type to a string, or use the longValue() method to convert the BigInteger type to a long type.

For example, for a bigint value of 16140901070782684196, you can use the following code to convert it to a BigInteger type:

String str = "16140901070782684196";
BigInteger bigInt = new BigInteger(str);

Then, you can use the toString() method to convert the BigInteger type to a string:

String str2 = bigInt.toString();

Or use the longValue() method to convert the BigInteger type to a long type:

long value = bigInt.longValue();

Note that if the bigint value exceeds the range of the long type, using the longValue() method will throw an ArithmeticException. In this case, you can consider using the BigInteger type for calculations or handling the value in another way.