Reputation: 1
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);
}
Upvotes: 0
Views: 269
Reputation: 180858
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
Upvotes: 1