Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert float to short with minimal loss of precision [closed]

I have this sine wave which generates floating point values (e.g. 0.37885) but I want them as shorts. Direct casting with short gives me a value of 0. so what is the solution?

Can anyone tell me how to do it - ideally without loss of precision - or minimal loss of precision if this is all that is possible?

like image 860
user3840530 Avatar asked Dec 07 '22 00:12

user3840530


2 Answers

public static short floatToShort(float x) {
    if (x < Short.MIN_VALUE) {
        return Short.MIN_VALUE;
    }
    if (x > Short.MAX_VALUE) {
        return Short.MAX_VALUE;
    }
    return (short) Math.round(x);
}

You'll loose the fractional part:

float    4 byte floating-point
double   8 byte floating-point (normal)
short    2 byte integer
int      4 byte integer (normal)
long     8 byte integer

Edit:

Maybe you wanted to know how to save the bits of a float (4 bytes) into an int (4 bytes): (http://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#floatToRawIntBits(float))

float x = 0.1f;
int n = Float.floatToRawIntBits(x);
float y = Float.intBitsToFloat(n);
like image 179
Joop Eggen Avatar answered Jan 11 '23 23:01

Joop Eggen


In principle, you could just multiply it by 100000, convert it to int, then subtract -32,767 and convert it to short. If that still puts it in the -32,767 to 32,767 range for all your values, that's likely the best you can do. Otherwise, you'll have to limit your precision and multiply by 10000.

And when you use the short of course you have to remember to divide it back down.

like image 41
Arwin Avatar answered Jan 11 '23 22:01

Arwin