Java - SNMP - Converting OctetString to Float

900 Views Asked by At

currently I am playing around with SNMP (snmp4j and SimpleSnmpClient) to get some information from a network device. This works as long as the result is a "normal" value like an integer.

If the value is an OctetString like 44:00:4f:00:30:00:4a:00:47:00:20:00:4d:00:49:00:58:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00 labelled as Unicode I can decode it as well but before I have to replace the ":"

  hex2AscII(sysDescr.replace(":", "")

with this method

static String hex2AscII(String hex) {
     StringBuilder ascii = new StringBuilder();
     for (int i = 0; i < hex.length(); i+=2) {
         String str = hex.substring(i, i+2);
         ascii.append((char)Integer.parseInt(str, 16));
     }

     return ascii.toString();
}

Now I want to get the value for a Voltage, the MiB says

  • OCTECT STRING (SIZE(4))
  • It should be changed to float format

OK I do the SNMP query and get as result: e6:d9:4c:41

witch should be a voltage around 12.8 Volt

Now I try to convert it to Float

    System.out.println("################# TestSection ################# ");
    int hex = 0xE6D94C41;
     f = Float.intBitsToFloat(hex);
    System.out.println(f);
    System.out.printf("%f", f);

and get -5.1308008E23

e6d94c41

So what is wrong with my code ?

1

There are 1 best solutions below

0
On

Here is the proper way of doing it in Java:

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class SnmpUtil{

    public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

     public static void main(String []args){

        byte[] bytes = SnmpUtil.hexStringToByteArray("e6d94c41");
        float f = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getFloat();
        System.out.println(f);
     }
}