0

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;
    }
2

1 Answer 1

1

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

8 Comments

I tried writing following function but did not output the exact value what I get in .net function. function String2Bin16bit(inputString) { //var str = "aabbcc"; // string var arr = []; // byte array for (var i = 0; i < inputString.length; i += 2) { // get chunk of two characters and parse to number arr[i / 2] = arr.push(parseInt(inputString.substr(i, 2), 16)); } return arr; }
Is that JavaScript? You're using arr[i / 2] = arr.push, which does not make sense. arr.push simply adds the value to the array, so no need for indices.
Yes it is javascript, still results are not same like .net function. I changed to 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)); // str = str + arr.push(parseInt(inputString.substr(i, 2), 16)); } return arr; }
@user228777: What about posting it in your question, since it's inscrutable without formatting in comments please.
@user228777: It works fine for me. What differences are there in the results?
|

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.