Skip to content

Instantly share code, notes, and snippets.

@davidfoerster
Created April 27, 2016 18:56
Show Gist options
  • Save davidfoerster/e8ffda0839d289137ff9ed74a950513a to your computer and use it in GitHub Desktop.
Save davidfoerster/e8ffda0839d289137ff9ed74a950513a to your computer and use it in GitHub Desktop.
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
class FPxToFloatClass
{
/**
* Converts a series of bytes in an FP*-like format to a native floating-
* point type.
*
* @param bytes A byte array containing an FP*-encoded number
* @param offset The offset of the first byte of the encoded number
* @param size The total amount of bytes used to encode the number
* @param integerits The length of the integral part of the encoded number
* in bits (little-endian); the remaining bits represent the fractional
* part.
* @return A number representing the encoded number in a native floating-
* point type
*/
public static double FPxToFloat( byte[] bytes, int offset, int size,
int integerBits )
{
if (offset < 0 || offset >= bytes.length)
throw new ArrayIndexOutOfBoundsException("offset");
if (size < 0 || size > bytes.length - offset)
throw new ArrayIndexOutOfBoundsException("size");
if ((long) integerBits - (long) size * Byte.SIZE < Integer.MIN_VALUE)
throw new ArithmeticException("integerBits");
double result = 0;
int exponent = integerBits - Byte.SIZE;
for (; offset < size; offset++, exponent -= Byte.SIZE) {
result += Math.scalb(bytes[offset] & 0xFF, exponent);
}
return result;
}
public static void main( String[] args ) throws IOException {
int integerBits = Integer.parseInt(args[0]);
byte[] data = readAll(System.in);
double f = FPxToFloat(data, 0, data.length, integerBits);
System.out.println(f);
}
private static byte[] readAll( InputStream s ) throws IOException {
byte[] buf1 = new byte[4 << 10];
ByteArrayOutputStream buf2 = new ByteArrayOutputStream();
int count;
while ((count = s.read(buf1)) >= 0)
buf2.write(buf1, 0, count);
return buf2.toByteArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment