[SNMP4J] More Info About Counter64 Bug
Jim Doble
jim.doble at tavve.com
Mon Aug 1 21:09:23 CEST 2005
I've been testing one of the proposed fixes to the problem in the
getBERLength method in the Counter64 class, and noticed that the code I
proposed needs a modification to handle the case where the Java will treat
the long value as negative (because a 64 bit unsigned value is being
represented as a Java long, which is a 64 bit signed value. The modified
code is:
public int getBERLength() {
if (value < 0L) {
return 11;
}
if (value < 0x80L) {
return 3;
}
if (value < 0x8000L) {
return 4;
}
if (value < 0x800000L) {
return 5;
}
if (value < 0x80000000L) {
return 6;
}
if (value < 0x8000000000L) {
return 7;
}
if (value < 0x800000000000L) {
return 8;
}
if (value < 0x80000000000000L) {
return 9;
}
return 10;
}
A similar approach, which looks a little more complicated but might be
faster if the values are uniformly distributed across the entire range of
possible values is to essentially perform the equivalent of a binary search:
public int getBERLength() {
if (value < 0L) {
return 11;
}
if (value < 0x80000000L) {
if (value < 0x8000L) {
if (value < 0x80L) {
return 3;
}
else {
return 4;
}
}
else {
if (value < 0x800000L) {
return 5;
}
else {
return 6;
}
}
}
else {
if (value < 0x800000000000L) {
if (value < 0x8000000000L) {
return 7;
}
else {
return 8;
}
}
else {
if (value < 0x80000000000000L) {
return 9;
}
else {
return 10;
}
}
}
}
If there is a preference for more concise code, the same logic can be
expressed as:
public int getBERLength() {
if (value < 0L) {
return 11;
}
if (value < 0x80000000L) {
if (value < 0x8000L) {
return value < 0x80L ? 3 : 4;
}
return value < 0x800000L ? 5 : 6;
}
if (value < 0x800000000000L) {
return value < 0x8000000000L ? 7 : 8;
}
return value < 0x80000000000000L ? 9 : 10;
}
More information about the SNMP4J
mailing list