代码之家  ›  专栏  ›  技术社区  ›  zahl

javascript中的签名int到签名char

  •  0
  • zahl  · 技术社区  · 2 年前

    我想在javascript中高效地将带符号的int转换为带符号的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));

    有没有其他有效的方法可以将带符号的int转换为带符号的char?(尤其是使用位运算符)

    1 回复  |  直到 2 年前
        1
  •  1
  •   Nguyễn Viết Minh Quân    2 年前

    您可以在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比特有符号整数(有符号字符)。这将保留的最后8位 x 并且丢弃剩余的比特,从而产生等效值的有符号整数。