How to convert hex representation of ipv4 back to string?

Does anyone have sample code for converting hex ipv4 address back to string?

like this? Hex to IP Converter - Convert Hexadecimal to IP - Online - Browserling Web Developer Tools

Thanks, but I'm looking for groovy code to do this.

You could try looking at some of the methods at the end of this copy of my driver...

https://raw.githubusercontent.com/sburke781/hubitat/kumoLocalControl/UnifiedThermostat/UnifiedThermostatUnitChild_Driver.groovy

1 Like
def hex2IP(hexStr) {
    ipStr=""
    for(i=0;i<hexStr.size();i=i+2){
        ipStr+="${hubitat.helper.HexUtils.hexStringToInt(hexStr.substring(i,i+2))}."
    }
    ipStr = ipStr.substring(0,ipStr.size()-1)
    return ipStr
}
3 Likes

Thanks for this. I did figure out how to do it. Here was my solution...

public static String hex2IP(String hex)
{
    String ip= "";

    for (int j = 0; j < hex.length(); j+=2) {
        String sub = hex.substring(j, j+2);
        int num = Integer.parseInt(sub, 16);
        ip += num+".";
    }

    ip = ip.substring(0, ip.length()-1);
    return ip;
}

2 Likes

The Groovy way: :wink:

public static String hex2IP(String hex)
{
  return org.codehaus.groovy.runtime.EncodingGroovyMethods.decodeHex(hex).collect{(it < 0 ? it + 256 : it)}.join('.')
}
4 Likes

Slick!

Agree, this is a really useful class that I haven't really looked at before. Thanks for the tip @Jost

2 Likes

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.