gpt4 book ai didi

JavaScript 简单 BitConverter

转载 作者:行者123 更新时间:2023-12-03 02:02:29 27 4
gpt4 key购买 nike

我需要为 JavaScript 制作简单的 C# BitConverter。我做了一个简单的BitConverter

class BitConverter{
constructor(){}
GetBytes(int){
var b = new Buffer(8)
b[0] = int;
b[1] = int >> 8
b[2] = int >> 16
b[3] = int >> 24
return b
}
ToInt(buffer){
return buffer[0] | buffer[1]<<8 | buffer[2] << 16 | buffer[3] << 24
}
}

GetBytes 给我的输出与 c# 相同,但 toInt 则不然......toInt 不会返回我放入 GetBytes 中的内容(更大的数字)示例:

var a = new BitConverter()
var e = 285128170;
var c =a.GetBytes(e);
var v = a.ToInt(c);
console.log(e) // 2851281703
console.log(c) // <Buffer 27 1b f3 a9 00 00 00 00>
console.log(v) //-1443685593

最佳答案

Javascript 将您的最终结果视为带符号的数字。您可以通过以 >>> 0 结束按位运算来解决此问题,这将强制符号位为 0。因此,对于您的示例:

class BitConverter{
GetBytes(int) {
var b = new Buffer(8)
b[0] = int;
b[1] = int >> 8
b[2] = int >> 16
b[3] = int >> 24
return b
}
ToInt(buffer) {
return (buffer[0] | buffer[1]<<8 | buffer[2] << 16 | buffer[3] << 24) >>> 0;
}
}

var converter = new BitConverter();
converter.ToInt(converter.GetBytes(2851281703)) // Returns 2851281703

来自documentation of zero-fill right shift :

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is always non-negative.

强调我的。

关于JavaScript 简单 BitConverter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49951290/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com