我正在尝试将下面的C#函数转换为Javascript,但运气不太好(请参阅下面的尝试(。
原始C#代码:
using System;
public class Program
{
const UInt16 MASK = 0xA001;
public static void Main()
{
byte[] test = System.Text.Encoding.ASCII.GetBytes("A TEST STRING");
ushort result = Program.GetChecksum(test);
}
public static ushort GetChecksum(byte[] pBytes)
{
ushort result = 0;
int vCount = pBytes.Length;
byte b;
for (int i = 0; i < vCount; i++)
{
b = pBytes[i];
for (byte cnt = 1; cnt <= 8; cnt++)
{
if (((b % 2) != 0) ^ ((result % 2) != 0))
{
result = (ushort)((result >> 1) ^ MASK);
}
else
{
result = (ushort)(result >> 1);
}
b = (byte)(b >> 1);
}
}
return result;
}
}
我的转换尝试:
Javascript:
const MASK = 0xA001;
const GetChecksum = (b: Buffer) => {
const result = Buffer.alloc(10).fill(0); // Don't know how much to alloc here
for (let i = 0; i < b.length; i++)
{
const byte = b[i];
for (let j = 1; j <= 8; j++)
{
const t1 = (byte % 2) !== 0;
const t2 = (result[i] % 2) !== 0;
result[i] = (!(t1 && t2) && (t1 || t2))
? ((result[i] >> 1) ^ MASK)
: (result[i] >> 1);
result[i] = byte >> 1;
}
}
return result;
}
const x = GetChecksum(Buffer.from('THIS IS A TEST','ascii'));
console.log(x.toString('ascii'));
特别是,我无法复制条件:(((b % 2) != 0) ^ ((result % 2) != 0))
,尽管我认为在我的尝试中存在多个问题。
如有任何帮助,我们将不胜感激!
该代码的javascript等价物是:
const MASK = 0xA001;
function getChecksum(bytes) {
let result = 0; // this is a number not a buffer
for (let b of bytes) { // for each byte in bytes (clearer than 'for' with an index 'i')
for (let ctn = 1; ctn <= 8; ctn++) { // same as C#
if (((b % 2) !== 0) ^ ((result % 2) !== 0)) { // same as C#
result = (result >> 1) ^ MASK; // same as C#
} else {
result = result >> 1; // same as C#
}
b = b >> 1; // same as C#
}
}
return result;
};
let buffer = Buffer.from("A TEST STRING", "ascii");
let result = getChecksum(buffer);
let checksumString = result.toString(16);
console.log(checksumString);
我希望这能给你一个线索:
if ((((b % 2) | 0) !== 0) ^ (((result % 2) >>> 0) !== 0)) {