Search code examples
javanode.jselasticsearch-painlesswktwkb

Java - Converting Hex string to double


Im attempting to decode the value of "Well-known Binary" format in Java. The following Node script does what I need

Buffer.from('A4C0A7DEBFC657C0', 'hex').readDoubleLE() // returns -95.1054608

My question is, what is the equivalent Java code? Nothing I have tried has given the same result.

See: https://en.wikipedia.org/wiki/Well-known_text_representation_of_geometry

I am running this as part of an ingest pipeline in OpenSearch, so I can't use 3rd party libraries.


Solution

  • I landed on a solution that doesn't require ByteBuffer as it's not available in painless.

    // convert hex string to byte array
    int l = hex.length();    
    byte[] data = new byte[l / 2];    
    for (int i = 0; i < l; i+= 2) {        
      data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)              
        + Character.digit(hex.charAt(i + 1), 16));        
    }
    
    // convert byte array to double
    long bits = 0L;
    for (int i = 0; i < 8; i++) {
      bits |= (data[i] & 0xFFL) << (8 * i);
    }
    return Double.longBitsToDouble(bits);