These are some code snippets I have made or found that may be useful.

Random Code Snippets

Language: Java

Description: This snippet is functionally identical to Java’s built-in string split method except for the fact that it only splits if the splitting term is not enclosed in a string. This can be especially useful for argument parsing for command line applications.

For example, assume we are launching a jar file called XML.jar, and we need to pass a file path as an argument. However, the file we need to pass has a space in the path name! If XML.jar implements this method in its argument parser, there is no problem. Although the arguments are separated by spaces, the space for the file path is in quotes, and therefore is ignored.

public static String[] splitExceptQuote(String input) {
        List<String> list = new ArrayList<String>();
        Matcher m = Pattern.compile("([^\"]\\S*|\".+?\")\\s*").matcher(input);
        while (m.find())
            list.add(m.group(1));
        return list.stream().toArray(String[]::new);
    }
 

Language: C

Description: This snippet converts a binary encoded IEEE754 floating point number into a single or double precision floating point number for a C program to read. This is useful specifically for reading the triangle vertex data from binary STL files in a C program.

double convertIEEE754toFloat(unsigned long number, char isDoublePrecise) {
    int mantissaShift = isDoublePrecise ? 52 : 23;
    unsigned long exponentMask = isDoublePrecise ? 0x7FF0000000000000 : 0x7f800000;
    int bias = isDoublePrecise ? 1023 : 127;
    int signShift = isDoublePrecise ? 63 : 31;
    int sign = (number >> signShift) & 0x01;
    int exponent = ((number & exponentMask) >> mantissaShift) - bias;
    int power = -1;
    double total = 0.0;
    for (int i = 0; i < mantissaShift; i++) {
        int calc = (number >> (mantissaShift - i - 1)) & 0x01;
        total += calc * pow(2.0, power);
        power--;
    }
    return (double)((sign ? -1 : 1) * pow(2.0, exponent) * (total + 1.0));
}