Skip to content

Instantly share code, notes, and snippets.

@panlw
Created July 16, 2019 07:28
Show Gist options
  • Save panlw/bc3da5c34761eaddee4c85fadf64997d to your computer and use it in GitHub Desktop.
Save panlw/bc3da5c34761eaddee4c85fadf64997d to your computer and use it in GitHub Desktop.
16 位整型转 32 位浮点型
package cn.kinco.test;
import org.junit.Test;
import java.nio.ByteBuffer;
import java.util.Arrays;
/**
* @author neo.pan
* @since 2019-07-16
*/
public class Int16sToFlt32sTest {
public static float[] convertInt16sToFlt32s(short[] int16s) {
final int flt32n = int16s.length / 2;
float[] flt32s = new float[flt32n];
ByteBuffer buffer = ByteBuffer.allocate(4);
for (int i = 0; i < flt32n; i += 1) {
buffer.putShort(int16s[i * 2]);
buffer.putShort(int16s[i * 2 + 1]);
flt32s[i] = buffer.getFloat(0);
buffer.clear();
}
return flt32s;
}
@Test
public void test1() {
final short[] int16s = new short[]{16256, -32768, 16384, 0};
final float[] flt32s = convertInt16sToFlt32s(int16s);
System.out.println(Arrays.toString(flt32s));
}
@Test
public void test2() {
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putFloat(1F);
System.out.println(buffer.getShort(0));
System.out.println(buffer.getShort(1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment