简体   繁体   中英

String to byte array

I have to convert a string to byte (16 bit) in JavaScript. I can do this in .net in following code but I have to change this for old classic asp App which uses JavaScript.

string strShared_Key = "6fc2e550abc4ea333395346123456789";
int nLength = strShared_Key.Length;
byte[] keyMAC = new byte[nLength / 2];
for (int i = 0; i < nLength; i += 2)
    keyMAC[i / 2] = Convert.ToByte(strShared_Key.Substring(i, 2), 16);

This is the JavaScript function but doesn't return same out put as above .net code.

function String2Bin16bit(inputString) {
        var str = ""; // string 
        var arr = [];       // byte array 
        for (var i = 0; i < inputString.length; i += 2) {
            // get chunk of two characters and parse to number 
            arr.push(parseInt(inputString.substr(i, 2), 16));
        }
        return arr;
    }

You want parseInt(x, 16) which will read x as a number and parse it as such bearing in mind that it's in base 16.

var str = "aabbcc"; // string
var arr = [];       // byte array
for(var i = 0; i < str.length; i += 2) {
    arr.push(parseInt(str.substr(i, 2), 16)); // get chunk of two characters and parse to number
}

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