0

I need to send an 8-byte string to an SNMP agent.

My number can be a big integer as a string. Due to the java limitation of signed bytes, I'm having a problem with some numbers.

For example, if num is "555", the SNMP agent receives the right value. if num is "666", the SNMP agent receives the wrong value, because, one of the byte in the array has a -ve value.

I did a bit & with 0xFF, still it doesn't work. How can I fix this? Thanks for your help!

 public static String stringNumToOctetString(String num) {
    BigInteger bi = new BigInteger(num);
    byte[] b = bi.toByteArray();

    int n = 8 - b.length;
    byte[] bVal = new byte[8]; //return must be 8 bytes
    for(int i=0; i<8; i++) {
        bVal[i] = (byte) 0;
    }
    int k = 0;
    for(int j=n; j<8; j++) {
        bVal[j] = (byte) (b[k++] & 0xFF);
    }
    return new String(bVal);
}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Eric
  • 1
  • What is a `-ve` value? Are you saying "negative" value? `byte` doesn't hold negative values. Is this Java? – Robert Harvey May 29 '13 at 20:27
  • This is in Java. Yes, "negative" value. In this case, one of the byte in b[] has it. – Eric May 29 '13 at 20:38
  • OK. What about the rest of my questions? Specifically, how is what you're doing causing SNMP to explode? Please be more specific. – Robert Harvey May 29 '13 at 20:39
  • See the line, `byte[] b = bi.toByteArray();` As explained in the example, if I pass "666", the `b[0]` has 2 and `b[1]` has -102 . If I pass "555" as a parameter, the `b[0]` has 2 and `b[1]` has 43. – Eric May 29 '13 at 20:55
  • Gotcha. See, this is why the `byte` in java sucks; it's a *signed* number. It has a range of -128 to +127, so you're not gonna get the values you want. – Robert Harvey May 29 '13 at 20:56
  • Why don't you just use an array of `int` instead of an array of `byte` to store the octet values. That way, you won't have problems with negative overflow anymore. – Robert Harvey May 29 '13 at 21:01
  • See also http://www.jguru.com/faq/view.jsp?EID=13647 – Robert Harvey May 29 '13 at 21:09
  • b[0] shoul be 2 b[1] should be 154 – Eric May 29 '13 at 21:10
  • Right, and 154 exceeds the range of a `byte`, which is why you're getting negative overflow. Use an array of `int` to store your values. – Robert Harvey May 29 '13 at 21:14

1 Answers1

1

Use an array of int to store your octet values, not an array of byte. byte is signed, and has a range of -128 to +127, so it's not going to work here, where you need values to go to 255.

Further Reading
http://www.jguru.com/faq/view.jsp?EID=13647

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501