我想将 byte[] 转换为 float,但只有前 4 个数字是正确的
I want to convert byte[] into float, but just the first 4 numbers are correct
所以我正在保存一个音频文件。我必须将 float[]
转换为 byte[]
。这很好用:
final byte[] byteBuffer = new byte[buffer.length * 2];
int bufferIndex = 0;
for (int i = 0; i < byteBuffer.length; i++) {
final int x = (int) (buffer[bufferIndex++] * 32767.0);
byteBuffer[i] = (byte) x;
i++;
byteBuffer[i] = (byte) (x >>> 8);
if (bufferIndex < 5) {
System.out.println(buffer[bufferIndex]);
System.out.println(byteBuffer[i - 1]);
System.out.println(byteBuffer[i]);
}
}
但是当我想读取字节并将其转换回浮点数时,只有前 4 个数字与旧数字匹配:
for (int i =0; i < length; i++) {
i++;
float val = (((audioB[i]) & 0xff) << 8) | ((audioB[i-1]) & 0xff);
val = (float) (val /32767.0);
if (bufferindex < 5) {
System.out.println(val);
System.out.println(audioB[i-1]);
System.out.println(audioB[i]);
}
bufferindex++;
}
输出:
0.07973075
0
0
0.149165
52
10
0.19944257
23
19
0.22437502
-121
25
---------
0.0
0
0
0.07971435
52
10
0.14914395
23
19
0.19943845
-121
25
0.22437209
为什么?
为什么不使用 java.nio.ByteBuffer
class?
而不是实施您自己的位移魔法
byte[] bytes = ByteBuffer.allocate(8).putFloat(1.0F).putFloat(2.0F).array();
ByteBuffer bb = ByteBuffer.wrap(bytes);
float f1 = bb.getFloat();
float f2 = bb.getFloat();
您将 4 个字节的浮点数据填充到每个样本的 2 个字节中。这显然会降低一些精度。提示:在你的第一个循环中进行反向计算(2 字节 -> 浮点数)并将结果与原始值进行比较,并查看像 x
.
这样的中间值
所以我正在保存一个音频文件。我必须将 float[]
转换为 byte[]
。这很好用:
final byte[] byteBuffer = new byte[buffer.length * 2];
int bufferIndex = 0;
for (int i = 0; i < byteBuffer.length; i++) {
final int x = (int) (buffer[bufferIndex++] * 32767.0);
byteBuffer[i] = (byte) x;
i++;
byteBuffer[i] = (byte) (x >>> 8);
if (bufferIndex < 5) {
System.out.println(buffer[bufferIndex]);
System.out.println(byteBuffer[i - 1]);
System.out.println(byteBuffer[i]);
}
}
但是当我想读取字节并将其转换回浮点数时,只有前 4 个数字与旧数字匹配:
for (int i =0; i < length; i++) {
i++;
float val = (((audioB[i]) & 0xff) << 8) | ((audioB[i-1]) & 0xff);
val = (float) (val /32767.0);
if (bufferindex < 5) {
System.out.println(val);
System.out.println(audioB[i-1]);
System.out.println(audioB[i]);
}
bufferindex++;
}
输出:
0.07973075
0
0
0.149165
52
10
0.19944257
23
19
0.22437502
-121
25
---------
0.0
0
0
0.07971435
52
10
0.14914395
23
19
0.19943845
-121
25
0.22437209
为什么?
为什么不使用 java.nio.ByteBuffer
class?
byte[] bytes = ByteBuffer.allocate(8).putFloat(1.0F).putFloat(2.0F).array();
ByteBuffer bb = ByteBuffer.wrap(bytes);
float f1 = bb.getFloat();
float f2 = bb.getFloat();
您将 4 个字节的浮点数据填充到每个样本的 2 个字节中。这显然会降低一些精度。提示:在你的第一个循环中进行反向计算(2 字节 -> 浮点数)并将结果与原始值进行比较,并查看像 x
.