简体   繁体   English

在JavaScript中将两个字节转换为带符号的16位整数

[英]Convert two bytes into signed 16 bit integer in JavaScript

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. 在JavaScript中,我需要将两个字节转换为16位整数,这样我就可以将音频数据流转换为带符号的PCM值数组。

Most answers online for converting bytes to 16 bit integers use the following, but it does not work correctly for negative numbers. 大多数在线将字节转换为16位整数的答案使用以下内容,但它对负数不起作用。

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

You need to consider that the negatives are represented in 2's compliment, and that JavaScript uses 32 bit integers to perform bitwise operations. 您需要考虑负数用2的恭维表示,并且JavaScript使用32位整数来执行按位运算。 Because of this, if it's a negative value, you need to fill in the first 16 bits of the number with 1's. 因此,如果它是负值,则需要用1填充数字的前16位。 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM