简体   繁体   English

我需要将8字节的字符串发送到SNMP代理,但是接收到错误的值

[英]I need to send an 8-byte string to an SNMP agent, but it's receiving the wrong values

I need to send an 8-byte string to an SNMP agent. 我需要将8字节的字符串发送到SNMP代理。

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. 由于带符号字节的Java限制,我遇到了一些数字问题。

For example, if num is "555", the SNMP agent receives the right value. 例如,如果num为“ 555”,则SNMP代理会接收正确的值。 if num is "666", the SNMP agent receives the wrong value, because, one of the byte in the array has a -ve value. 如果num为“ 666”,则SNMP代理收到错误的值,因为数组中的字节之一具有-ve值。

I did a bit & with 0xFF, still it doesn't work. 我做了一些与0xFF,仍然无法正常工作。 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);
}

Use an array of int to store your octet values, not an array of byte . 使用int数组存储八位字节值,而不是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. byte是带符号的,范围为-128到+127,因此在这里需要将值设置为255的地方不起作用。

Further Reading 进一步阅读
http://www.jguru.com/faq/view.jsp?EID=13647 http://www.jguru.com/faq/view.jsp?EID=13647

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM