Skip to content

Instantly share code, notes, and snippets.

@alcides
Created May 29, 2020 19:50
Show Gist options
  • Save alcides/0bedeabd0c078298af27d544a64df307 to your computer and use it in GitHub Desktop.
Save alcides/0bedeabd0c078298af27d544a64df307 to your computer and use it in GitHub Desktop.
Convert Java floats and doubles to LLVM float and double Hex literals.
package com.alcidesfonseca.llvmgenerator;
/*
* Helper functions to convert float and double constants to LLVM format
*
* Inspired by Scala Native
* */
public class ConstantUtils {
public String floatToLLVM(float f) {
return "0x" + toHexString(Double.doubleToRawLongBits((double) f));
}
public String doubleToLLVM(double d) {
return "0x" + toHexString(Double.doubleToRawLongBits(d));
}
private String toHexString(long l) {
int count = (l == 0L) ? 1 : ((64 - Long.numberOfLeadingZeros(l)) + 3) / 4;
StringBuilder buffer = new StringBuilder(count);
long k = l;
do {
long t = k & 15L;
if (t > 9) {
t = t - 10 + 'A';
} else {
t += '0';
}
count -= 1;
buffer.insert(0, (char) t);
k = k >> 4;
} while (count > 0);
return buffer.toString();
}
}
package com.alcidesfonseca.llvmgenerator;
public class Test {
public static void main(String[] args) {
ConstantUtils cu = new ConstantUtils();
System.out.println(cu.floatToLLVM(3.2f) + " == 0x40099999A0000000");
System.out.println(cu.floatToLLVM(3.9f) + " == 0x400F333340000000");
System.out.println(cu.doubleToLLVM(3.2));
System.out.println(cu.doubleToLLVM(3.9));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment