sách gpt4 ai đã đi

JavaScript BitConverter đơn giản

In lại 作者:行者123 更新时间:2023-12-03 02:02:29 28 4
mua khóa gpt4 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) //
console.log(v) //-1443685593

1 Câu trả lời

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

Từ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/

28 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com