3

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.

2
  • 1
    You should at least return uint[] or rename the method. Commented Mar 30, 2018 at 11:15
  • @C.Evenhuis, Yes you are correct, I missed that. Commented Mar 30, 2018 at 11:30

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. is the js BigInteger signed?
There are several implementations of big integer in javascript. Mist popular has constructor argument as I remember, with which you can control whether it is signed or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.