Gangmax Blog

自由之思想,独立之精神

Protobuf uint64 & Java Long

The post records the issue I met when using protobuf uint64 and Java Long.

When we define some protobuf message with ab “uint64”(unsigned int64) type field in it, and decode the corresponding binary payload to a Java object, the uint64 field in protobuf format will be mapped to a Long type Java field.

An potential issue may happen in such case: if the uint64 number is bigger than “Long.MAX_VALUE“, it will be converted to a negative Java Long value. For example:

1
# Note: 9223372036854775807 is Long.MAX_VALUE:
2
uint64 14001908927091871061 is mapped to Java long -4444835146617680555
3
uint64 11141610350324941563 is mapped to Java long -7305133723384610053

This caused confusions and issues. To fix it, use the code below to convert:

1
String id = "14001908927091871061";
2
Long long1 = Long.parseUnsignedLong(id);
3
System.out.println("id: " + id);
4
5
id = "-4444835146617680555";
6
Long longId = Long.parseLong(id);
7
System.out.println("longId: " + Long.toUnsignedString(longId));
8
9
// The code above prints the following lines:
10
id: 14001908927091871061
11
longId: 14001908927091871061

Comments