在JavaScript中将两个字节转换为带符号的16位整数 [英] Convert two bytes into signed 16 bit integer in JavaScript

查看:618
本文介绍了在JavaScript中将两个字节转换为带符号的16位整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,我需要将两个字节转换为16位整数,以便可以将音频数据流转换为带符号PCM值的数组.

In JavaScript, I need to convert two bytes into a 16 bit integer, so that I can convert a stream of audio data into an array of signed PCM values.

大多数在线将字节转换为16位整数的答案都使用以下内容,但对于负数不能正常使用.

Most answers online for converting bytes to 16 bit integers use the following, but it does not work correctly for negative numbers.

var result = (((byteA & 0xFF) << 8) | (byteB & 0xFF));

推荐答案

您需要考虑的是,负数表示为2,并且JavaScript使用32位整数执行按位运算.因此,如果它是负值,则需要用1填充数字的前16位.因此,这是一个解决方案:

You need to consider that the negatives are represented in 2's compliment, and that JavaScript uses 32 bit integers to perform bitwise operations. Because of this, if it's a negative value, you need to fill in the first 16 bits of the number with 1's. So, here is a solution:

var sign = byteA & (1 << 7);
var x = (((byteA & 0xFF) << 8) | (byteB & 0xFF));
if (sign) {
   result = 0xFFFF0000 | x;  // fill in most significant bits with 1's
}

这篇关于在JavaScript中将两个字节转换为带符号的16位整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆