how to convert string to array of 32 bit integers? - javascript

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)]);
}

Related

return a string where each digit is repeated a number of times equals to its value

I'm trying to solve a problem: Given a string made of digits [0-9], return a string where each digit is repeated a number of times equals to its value. I did the repetition of numbers, how next - I don’t know.
function explode(s) {
for (let i=0; i < s.length; i++){
let y = s[i].repeat(s[i]);
console.log(y);
}
}
You were only missing a result string to collect the parts
function explode(input) {
let result = '';
let s = input.toString(); // So that input can also be a number
for (let i=0; i < s.length; i++){
let y = s[i].repeat(s[i]);
result += y;
}
return result;
}
Javascript is good at coercing numbers to string and vice versa but I prefer to make clear when a numerical character is being treated as a number and when it is intended to be a string.
My snippet tests processing of numbers, string representations of numbers, strings having mixtures of number and letter characters, and letter strings.
it makes use of array.split() to for the character array, array.map() to process the characters (including parseInt to formally change the character to a number when used as the argument the string.repeat(), and array.join() to return the desired numeric string after processing:
let number = 6789;
let numberString = "12345";
let badNum = "3bad2Number";
let noNum = "justLetters";
console.log(expandNums(number));
console.log(expandNums(numberString));
console.log(expandNums(badNum));
console.log(expandNums(noNum));
function expandNums(numOrString) {
let numString = numOrString.toString();
let chars = numString.split('');
let processed = chars.map(char => char.repeat(parseInt(char)));
return processed.join('');
} // end function expandNums
The function performs well under all use situations tested, so is unlikely to throw an error if a bad argument is passes. It also does a good job with the mixed letter/number example.

Iterate through an array and convert all character codes to characters?

I've coded myself into a hole and though it would be easier to start again, there is still a lesson to be learned here (it's just practice anyway).
I'm building a caesar cipher which will accept two parameters: the message, and the cipher key. Each letter is compared to its corresponding letter in the cipher key, then changed to a new character code.
I'm having a hell of a time figuring out how to turn an array of character codes into an array (or better yet, a string) of characters.
Here's my code:
function cipher(message, cipherKey) {
//convert the message and cipher key to arrays of their character codes
var messageArr = message.toLowerCase().split("").map(x => x.charCodeAt() - 97);
var cipherKeyArr = cipherKey.toLowerCase().split("").map(x => x.charCodeAt() - 97);
//create new array for the ciphered array, which will turn back to a string
var cipheredArr = [];
//loop through both the cipher key value and message key value to
//create the ciphered array
for (var i = 0; i < messageArr.length; i++) {
cipheredArr[i] = messageArr[i] + cipherKeyArr[i];
if (cipheredArr[i] >= 26) {}
}
//go through the ciphered array and make it loop back through
//the alphabet once it goes past z
for (var i = 0; i < cipheredArr.length; i++) {
if (cipheredArr[i] >= 26) {cipheredArr[i] = cipheredArr[i] - 26;}
}
//display on webpage
return cipheredArr;
}
So the cipheredArr is an array of numbers (character codes) but I can't find a good way to iterate through it and change them back into letters. The .fromCharCode() syntax is confusing me for this purpose.
To get an array of characters for an array of character codes, use map:
var chars = codes.map(code => String.fromCharCode(code));
(Note: Just codes.map(String.fromCharCode) won't work, String.fromCharCode would make inappropriate use of the second and third arguments map passes the callback.)
To get a string from those codes:
// ES2015+
var str = String.fromCharCode(...codes);
// ES5 and earlier:
var str = String.fromCharCode.apply(null, codes);
fromCharCode returns a string made up of the code units you pass it as discrete arguments (MDN | spec).

How do I store a string as a typed array?

I’m trying to convert a string to a typed array (specifically a Uint8Array) in javascript. I’m trying to store the ASCII values of the characters of the string as individual array elements.
var myString = 'foo bar baz " >';
var arr = new Uint8Array(myString);
console.log(arr.length); // Why is this 0?
Why is it that the length of the array I create is 0?
From this link: http://jsperf.com/string-to-uint8array
This is the fastest way to create a Uint8Array from a string:
var str = "your string here";
var uint = new Uint8Array(str.length);
for(var i=0, j=str.length; i<j; ++i){
uint[i] = str.charCodeAt(i);
}
As pointed out, your error comes from the fact that the constructor does not accept a string argument. Instead, you can allocate an array based on the size of the string, and insert the characters manually.
From this link you can see that your constructor needs a length or an array for a single parameter.
I would suggest this :
var myString = 'foo bar baz " >';
var arr = new Uint8Array(myString.length);
console.log(arr.length);

How to split the string in to different parts

I want to split the string in to different parts. I will have some string which will be generated dynamically which will contains 500 characters. I want to split in to 5 parts. What i mean is i want to take 100 characters in to array[0], next 100 characters in array[1] ....
Example:
var string = "kjfaorj.......................................................";
array[0] = "kjfaorj..... up to 100 characters";
array[1] = " next 100 characters ";
..........................
..........................
if(str.length % 100 == 0) //If the string contains exactly 500 or 400...etc
count = str.length / 100;
else
count = str.length / 100 +1; //If the string contains exactly 505 or 417...etc
for(var i=0;i<count;i++)
array[i] = s.substring(i*100,(i*100)+(100));
Second approach is good for dynamic string
Try this:
var string= "kjfaorj.......................................................";
var array=[];
array[0] = string.substring(0,99);
array[1] = string.substring(100,199);
array[2] = string.substring(200,299);
array[3] = string.substring(300,399);
array[4] = string.substring(400,499);
The following loop will split up any string in pieces of 100 characters. The last element of the array will contain the remaining number of characters (but never more than 100).
If you’re certain your initial string will contain exactly 500 characters, you’ll always get an array of five elements, each one containing 100 characters.
var str = "kjfaorj....................................................... etc.";
for(var arr = [], i = 0; i < str.length - 1; i += 100) {
arr.push(str.substr(i, 100));
}
The difference between substr and substring is that substr expects the length of the substring, whereas substring expects the first and the last index.
As i see "jquery" tag in your question,i want to introduce my powerful JQuery Plugin .
Its String As JQuery
one of features of this plugin is to convert a String to Array : Each n consecutives characters of String is an item in this Array.
Syntax
var myarray=$(myString).toStrArray(eachN);
for you case , you can use it as following ;
var string = "kjfaorj.......................................................";
var myarray=$(string).toStrArray(100);
Demo
http://jsfiddle.net/abdennour/E8LhJ/
Here's a more generic function for any string length:
function splitupString(str,chunklen){
str = str.split('');
var chunks = Array((str.length/chunklen)^0).join(',').split(',');
return chunks
.map(function(){return this.splice(0,chunklen).join('');},str)
.concat(str.join(''));
}
// usage example
var strsplitted = splitupString('123456789012345678901234567890123',5);
//=> [12345,67890,12345,67890,12345,67890,123]
jsFiddle example
If you need to split the string to exactly 100 characters chunks then
var foo = bar.match(/.{100}/g);
If you need to split to chunks having no more than 100 characters, then
var foo = bar.match(/.{1,100}/g);

transfer special charcter to normal charcter

I am try to load city name from the XML file using javascript AJAX and finally success on them.
var region=Ahmadābād,Sūrat,Vadodara,Rājkot,Bhāvnagar,Jāmnagar,Nadiād,Gāndhīnagar,Jūnāgadh,Surendranagar
This is my output; in this output some charcter are non standard US ASCII and I want to change into normal chars, like:
var region:- Ahmadabad,Surat,Vadodara,Rajkot,Bhavnagar,Jamnagar,Nadiad,Gandhinagar,Junagadh,Surendranagar
How can I do that?
This is a pure javascript solution though it is not optimal and might perform not well:
// create a character map to convert one char to another
var charMap = {
"ā" : "a",
"ū" : "u"
};
var region="Ahmadābād,Sūrat,Vadodara,Rājkot,Bhāvnagar,Jāmnagar,Nadiād,Gāndhīnagar,Jūnāgadh,Surendranagar";
// split original string into char array
var chars = region.split('');
// init new array for conversion result
var charsConverted = [];
// convert characters one by one
for(var i = 0; i < chars.length; i++){
var char = chars[i];
// this will try to use a matching char from char map
// will use original if no pair found in charMap
charsConverted.push( charMap[char] || char);
}
// join array to string
var result = charsConverted.join('');
alert(region);
alert(result);
Again this is just an idea and might need a lot of tweaking.
Code in action: http://jsfiddle.net/L5Yzf/
HTH

Categories