gpt4 book ai didi

c# - 将 C# 转换为 NodeJS

转载 作者:搜寻专家 更新时间:2023-11-01 00:29:57 24 4
gpt4 key购买 nike

您好,我正在尝试将此 C# 函数转换为 NodeJS,但它不起作用我真的不知道哪里出了问题让我展示一些代码和输出

C#:

private static byte[] ConvertMsg(byte[] message, byte type = 255, byte cmd = 255)
{
int msgLength = message.Length;
byte[] bArray = new byte[msgLength + 3];
bArray[0] = type;
bArray[1] = cmd;
Buffer.BlockCopy(message, 0, bArray, 2, msgLength);
bArray[msgLength + 2] = 0;
return bArray;
}

static void Main()
{

byte[] encrypted = ConvertMsg(Encoding.Default.GetBytes("hi"),3,3);
Console.WriteLine($"Encrypted: {Convert.ToBase64String(encrypted)}");

Console.ReadKey();
}

输出:

AwNoaQA=

Node :

function ConvertMsg(message, type=255, cmd=255){
let length = message.length;
let bArray = Buffer.alloc(length+3);
bArray[0] = type;
bArray[1] = cmd;

bArray.copy(message,0,length);

bArray[length + 2] = 0;
return bArray;
}

let encrypted = ConvertMsg(Buffer.from("hi"),3,3);
console.log(encrypted.toString("base64"));

输出:

AwMAAAA=

如您所见,输出不一样,非常感谢任何帮助,请在回答时解释我想了解更多,谢谢。

最佳答案

根据 Buffer documentation , .copy(target[, targetStart[, sourceStart[, sourceEnd]]])

Copies data from a region of buf to a region in target even if the target memory region overlaps with buf.

这里

// means copy 'bArray' starting from length to 'message' starting from 0
bArray.copy(message, 0, length);

您不要复制 message 的内容至 bArray .你做相反的事情 - 你复制 bArray内容,即 [3, 3, 0, 0, 0]现在到message ,并实际覆盖您的消息。

然后,你输出这个bArray ,结果为 AwMAAAA=这是 [3, 3, 0, 0, 0] 的 Base64 表示.

您可能希望以这种方式更改您的功能:

function ConvertMsg(message, type=255, cmd=255){
let length = message.length;
let bArray = Buffer.alloc(length + 3);

bArray[0] = type;
bArray[1] = cmd;

// means copy 'message' starting from 0 to 'bArray' starting from 2
message.copy(bArray, 2);

bArray[length + 2] = 0;
return bArray;
}

关于c# - 将 C# 转换为 NodeJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40298231/

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