I am trying to convert the following C# function into Javascript, but I haven't had much luck (see my attempt below).
Original C# code:
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;
}
}
My conversion attempt:
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'));
In particular, I'm not able to replicate the condition: (((b % 2) != 0) ^ ((result % 2) != 0)), although I think there are multiple issues in my attempt.
Any help here would be appreciated!