Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I don't know C# very well and I get stuck. How this C# function would look in node/javascript?
C#
static byte[] HashToBytes(string hash, bool reversed = false)
        {
            byte[] ret = new byte[hash.Length / 3];
            for (int i = 0; i < ret.Length; i++)
            {
                ret[i] = byte.Parse(hash.Substring((reversed ? ret.Length - i - 1 : i) * 3, 3));
            }
            return ret;
        }


What I have tried:

I tried making it myself but if hash would be 155122110083109073090099, on javascript I get C0D12583FE7A009B instead of 635A496D536E7A9B, like how I get on C#
JavaScript
function HashToBytes(hash) {
    var byte = await Buffer.alloc(hash.length / 3)
    for(var i = 0; i < byte.length; i++) {
      byte[i] = await Buffer.from(hash.substring((byte.length - i - 1) * 3, 3))
    }
}
Posted
Updated 11-Aug-19 21:49pm

1 solution

Your C# code:
C#
ret[i] = byte.Parse(hash.Substring((reversed ? ret.Length - i - 1 : i) * 3, 3));
Means if the reversed flag is false then use the next byte in sequence.

Your Javascript code:
JavaScript
byte[i] = await Buffer.from(hash.substring((byte.length - i - 1) * 3, 3))
Is selecting the source data bytes in reverse order. Just use the value of i as the offset, thus:
JavaScript
byte[i] = await Buffer.from(hash.substring((i) * 3, 3))
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900