Number Utils

I have, on a few occasions, needed some utilities to convert numbers to binary, so I created a class that will do this for the various numbers in Java and am making it available on GitHub for people to do what they will.

For example, to convert from a short to binary I do:

public static byte[] convertToBinary(short s)
{
    byte[] retVal = new byte[2];

    retVal[0] = (byte) ((s >>> 0) & 0xFF);
    retVal[1] = (byte) ((s >>> 8) & 0xFF);

    return retVal;
}

and to get it back to a short I do:

public static short convertToShort(byte[] bytes)
{
    short retVal = 0;
    int i,j;

    if(bytes.length > 1)
    {
        i = (int) bytes[0];
        j = (int) bytes[1];

        if(j < 0) j = -(j ^ 0xff) - 1;
        if(i < 0) i = -(i ^ 0xff) - 1;

        retVal = (short) ((i << 0) + (j << 8));
    }
    else if(bytes.length == 1)
    {
        i = (int) bytes[0];
        retVal = (short) (i << 0);
    }

    return retVal;
}

Note that I support an array of 1 or 2 bytes, so that you can pack things as you want.

There are a number of methods to take a number and encoded it onto an interval using steps. This allows you to compact a number into a small binary representation with some loss flexibility and/or accuracy.

I also wrote a really simple method that returns the closest prime less than or equal to any number up to 11,000. The goal was for supporting prime array sizes in hash tables. Finally there is a method to convert the sum of all numbers up to and including the number you pass in. This is a nice example of using an algorithm instead of brute force.

public static int calculateSum(int n)
{
    int retVal = 0;

    if(n%2==1)
    {
        retVal = ((n-1)/2)*n;
        retVal += n;
    }
    else
    {
        retVal = (n/2)*n;
        retVal += n/2;
    }

    return retVal;
}

GitHub Repository

java