Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js to c# converting

Tags:

c#

node.js

I have this function is Node.js

// @param {BigInteger} checksum
// @returns {Uint8Array}

function checksumToUintArray(checksum) {
  var result = new Uint8Array(8);
  for (var i = 0; i < 8; ++i) {
    result[7 - i] = checksum.and(31).toJSNumber();
    checksum = checksum.shiftRight(5);
  }
  return result;
}    

What would be the equivalent in c#?

I'm thinking:

    public static uint[] ChecksumToUintArray(long checksum)
    {
        var result = new uint[8];
        for (var i = 0; i < 8; ++i)
        {
            result[7 - i] = (uint)(checksum & 31);
            checksum = checksum >> 5;         
        }
        return result;
    }

But I'm no sure. My main dilemma is the "BigInteger" type (but not only). Any help would be appropriated.

like image 498
zig Avatar asked Jan 20 '26 14:01

zig


1 Answers

UInt8 is "unsigned 8-bit integer". In C# that's byte, because uint is "unsigned 32-bit integer". So UInt8Array is byte[].

Javascript BigInteger corresponds to C# BigInteger (from System.Numerics dll or nuget package), not to long. In some cases, long might be enough. For example, if BigInteger in javascript algorithm is used only because there is no such thing as 64bit integer in javascript - then it's fine to replace it with long in C#. But in general, without any additional information about expected ranges - range of javascript BigInteger is much bigger than range of C# long.

Knowing that, your method becomes:

public static byte[] ChecksumToUintArray(BigInteger checksum) {
    var result = new byte[8];
    for (var i = 0; i < 8; ++i) {
        result[7 - i] = (byte) (checksum & 31);
        checksum = checksum >> 5;
    }
    return result;
}
like image 158
Evk Avatar answered Jan 22 '26 05:01

Evk