最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

audio - Convert two bytes into signed 16 bit integer in JavaScript - Stack Overflow

programmeradmin3浏览0评论

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

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));
Share Improve this question asked Jul 11, 2016 at 2:41 Rick GiulyRick Giuly 1,0431 gold badge15 silver badges20 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 14

You need to consider that the negatives are represented in 2's pliment, 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
}
发布评论

评论列表(0)

  1. 暂无评论