简体   繁体   中英

how to convert string to array of 32 bit integers?

I want to send the string to an encryption function which accepts an array of four (32-bit) integers. So how to convert string to array of 32 bit integers in javascript and divide it to send it to function?

This smells of homework, but here you go.


Method 1:

Assuming you want to convert four characters in a string to ints, this will work:

// Declare your values.
var myString = "1234";

// Convert your string array to an int array.
var numberArray[myString.length];
for (var i = 0; i < myString.length]; i++)
{
    numberArray[i] = int.parseInt(myString[i]);
}

// Call your function.
MyEncryptionFunction(numberArray);

Method 2:

Assuming you want to convert four characters to the numeric values of their chars, this will work:

// Declare your values.
var myString = "1,2,3,4";

// Convert your string array to an int array.
var numberArray[myString.length];
for (var i = 0; i < myString.length]; i++)
{
    numberArray[i] = myString.charCodeAt(i);
}

// Call your function.
MyEncryptionFunction(numberArray);

Method 3:

Assuming you want to split a group of four numbers separated by a consistent delimiter, this will work.

// Declare your values.
var splitter = ",";
var myString = "1,2,3,4";

// Convert myString to a string array.
var stringArray[] = myString.split(splitter);

// Convert your string array to an int array.
var numberArray[stringArray.length];
for (var i = 0; i < stringArray.length]; i++)
{
    numberArray[i] = int.parseInt(stringArray[i]);
}

// Call your function.
MyEncryptionFunction(numberArray);

Use string.charCodeAt(i) , to get the numeric char code of string string at position i . Depending on your used encryption, you can apply an own compression method, to combine multiple char codes (most char codes are far smaller than 32 bits).

Example of separating a string in an array consisting of pairs (4 chars):

var string = "A sstring dum doo foo bar";
var result = [];
string += Array((5-(string.length%4))%5).join(" "); //Adding padding at the end
for(var i=3, len=string.length; i<len; i+=4){
    result.push([string.charCodeAt(i-3), string.charCodeAt(i-2),
             string.charCodeAt(i-1), string.charCodeAt(i)]);
}

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