简体   繁体   English

如何在Javascript中将两个8位转换为16位,反之亦然?

[英]How to convert two 8-bits to 16-bits and vice versa in Javascript?

I know this has been asked before, but I have not been able to reach a solution. 我知道以前曾经问过这个问题,但我还没有找到解决办法。 I apologize if the topic is duplicated, but I think it's not. 如果主题重复,我道歉,但我认为不是。

I have a number extracted from a Uint16Array to convert to a pair of 8-bit numbers and does it well, but when I want to convert from these two 8-bit numbers to the the first number I can't get it. 我有一个从Uint16Array中提取的数字转换成一对8位数字并且做得很好,但是当我想从这两个8位数字转换为第一个数字时,我无法得到它。

 var firstNumber = 1118; // extracted from Uint16Array var number8Bit1 = firstNumber & 0xff; var number8Bit2 = ((firstNumber >> 8) & 0xff); console.log(number8Bit1, number8Bit2); // 94, 4 var _firstNumber = (((number8Bit1 & 0xff) << 8) | (number8Bit2 & 0xff)); console.log(_firstNumber); // 24068 <-- 1118 

You would be so kind as to help me please. 你会非常友善地帮助我。 Thank you. 谢谢。

You swapped the bytes: 你交换了字节:

var _firstNumber = (((number8Bit2 & 0xff) << 8) | (number8Bit1 & 0xff));

You have to do the reverse of the extraction when combining. 组合时,您必须执行与提取相反的操作。

var firstNumber = 1118; // extracted from Uint16Array

var high = ((firstNumber >> 8) & 0xff);
var low = firstNumber & 0xff;

console.log(high, low); // 4, 94

var _firstNumber = (((high & 0xff) << 8) | (low & 0xff));

console.log(_firstNumber); // 1118

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

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