javascript 中的signed int 到signed char

问题描述 投票:0回答:1

我想在javascript中有效地将signed int转换为signed char。 我试过:

function convertByModular(n) {
    return ((((n + 128) % 256) + 256) % 256) - 128;
}

function convertByTypedArray(n) {
    return new Int8Array([n])[0];
}
console.log(convertByModular(-129));
console.log(convertByTypedArray(-129));

还有其他有效的方法将signed int 转换为signed char 吗? (特别是使用位运算符)

javascript type-conversion
1个回答
0
投票

您可以在 JavaScript 中使用

<<
(左移)和
>>
(右移)运算符来限制整数的值,从而将有符号整数转换为有符号字符。例如,要将有符号整数
x
转换为有符号字符,您可以执行以下操作:

function toSignedChar(x) {
   return (x << 24 >> 24); // 24 bits left shift and then 24 bits right shift
}

// For example
console.log(toSignedChar(300)); // -28
console.log(toSignedChar(-300)); // 28

在上面的示例中,

x
使用 24 位左移然后 24 位右移转换为 8 位有符号整数(signed char)。这将保留
x
的最后 8 位并丢弃剩余位,产生等效值的有符号整数。

© www.soinside.com 2019 - 2024. All rights reserved.