Skip to content

Instantly share code, notes, and snippets.

@bluelhf
Created April 22, 2025 18:23
Show Gist options
  • Save bluelhf/fddd96b1dfcf13286367d56efc174a5e to your computer and use it in GitHub Desktop.
Save bluelhf/fddd96b1dfcf13286367d56efc174a5e to your computer and use it in GitHub Desktop.
Convert 4x4 matrices in HEX Q31.32 to decimal, requires Java 21 with --enable-preview.
import java.util.Arrays;
// run with java QC.java --enable-preview
void main() {
final String input = """
0000:0000:B541:00AA 0000:0000:0000:0000 0000:0000:B4CB:D1C9 FFFF:FFE9:5F62:D8D0
0000:0000:0000:0000 0000:0001:0000:0000 0000:0000:0000:0000 FFFF:FFF0:0000:0000
FFFF:FFFF:4B37:2E37 0000:0000:0000:0000 0000:0000:B541:00AA FFFF:FFFF:F87D:11F0
0000:0000:0000:0000 0000:0000:0000:0000 0000:0000:0000:0000 0000:0001:0000:0000
""";
/*final String input = """
0000:0001:0000:0000 0000:0000:0000:0000 0000:0000:0000:0000 FFFF:FFF0:0000:0000
0000:0000:0000:0000 0000:0001:0000:0000 0000:0000:0000:0000 FFFF:FFF0:0000:0000
0000:0000:0000:0000 0000:0000:0000:0000 0000:0001:0000:0000 FFFF:FFF0:0000:0000
0000:0000:0000:0000 0000:0000:0000:0000 0000:0000:0000:0000 0000:0001:0000:0000
""";*/
final double[] seq = Arrays.stream(input.split("\n"))
.flatMap(line -> Arrays.stream(line.split(" "))
.mapToDouble(x -> convertToDecimal(x.trim()))
.boxed()
).mapToDouble(x -> x).toArray();
final double[][] matrix44 = new double[][] {
{seq[ 0], seq[ 1], seq[ 2], seq[ 3]},
{seq[ 4], seq[ 5], seq[ 6], seq[ 7]},
{seq[ 8], seq[ 9], seq[10], seq[11]},
{seq[12], seq[13], seq[14], seq[15]}
};
printMatrix(matrix44);
}
void printMatrix(double[][] matrix) {
for (double[] row : matrix) {
for (int len = row.length, i = 0; i < len; ++i) {
System.out.printf("%+.8f", row[i]);
if (i < len - 1) {
System.out.print(" ");
}
}
System.out.println();
}
}
double convertToDecimal(String hex) {
final String[] parts = hex.split(":");
final String wholeWord = parts[0] + parts[1];
final String fractWord = parts[2] + parts[3];
final int whole = Long.valueOf(wholeWord, 16).intValue();
final double fract = Long.valueOf(fractWord, 16) / Math.pow(2, 32);
return Double.valueOf(whole + fract);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment