简体   繁体   中英

Is there an equivalent for C# Enumerable for converting string to byte array in NodeJs?

I'm Sending Hex string to a function and return it as Byte array using c# , but now the requirement is to do this in NodeJs .

i searched too much about this but non solutions gave me the same result

here is my c# code with this hex string

    `8001000501335688003300020002000200`

    public static byte[] StringToByteArray(string hex)
    {
        var byteArray = Enumerable.Range(0, hex.Length)
                         .Where(x => x % 2 == 0)
                         .Select(x =>Convert.ToByte(hex.Substring(x,2),16))
                         .ToArray();
        return byteArray;
    }

i tried this code in NodeJs but i didn't get the same result

    function StringToByteArray(hex) {
        var rangebytes = range(0, hex.length).filter(x => x % 2 == 0)
        var filteredHex = rangebytes.match(x => 
            Buffer.from(hex.substring(x, 2), "utf8"));

        return filteredHex;
     }

    function range(start, count) {
        return Array.apply(0, Array(count))
        .map(function (element, index) {
                        return index + start;
                });
      }  

And here is the result from c# code http://prntscr.com/m7xnzg

This function will convert a hex string to a byte array in Node.js:

 function hexStringToByteArray(hexStr) { let a = []; for(let c = 0; c < hexStr.length; c += 2) { a.push(parseInt(hexStr.substr(c, 2), 16)); } return a; } console.log("Result: ", hexStringToByteArray("8001000501335688003300020002000200")); 

It is good to use Buffer API for this:

Buffer.from('8001000501335688003300020002000200', 'hex')

// <Buffer 80 01 00 05 01 33 56 88 00 33 00 02 00 02 00 02 00>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM