Convert two bytes into signed 16 bit integer in JavaScript

丶灬走出姿态 提交于 2019-12-01 01:58:46

问题


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.

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));

回答1:


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
}


来源:https://stackoverflow.com/questions/38298412/convert-two-bytes-into-signed-16-bit-integer-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!