You can use one first split
to transform the list into an array, and then an map
to generate a new array by transforming each string within it into a number:
function bytesFromWords (string) {
var bytes = [];
for(var i = 0; i < string.length; i++) {
var char = string.charCodeAt(i);
bytes.push(char >>> 8);
bytes.push(char & 0xFF);
}
return bytes;
}
var lista = bytesFromWords('teste soPT').toString();
var strArray = lista.split(',');
var numArray = strArray.map(function(item) {
return parseInt(item, 10);
});
console.log(numArray);
It would be so much nicer to do var numArray = lista.split(',').map(parseInt)
. However, the map
passes the element index as the second parameter, while the parseInt
receives the conversion base as the second parameter, which spoils the result. To enable such a syntax, you would need to create a function that parseInt
with the second fixed argument:
function myParseInt(num) {
return parseInt(num, 10);
}
// Aí sim:
var numArray = lista.split(',').map(myParseInt);
You want to reverse the operation of
bytesFromWords
(returning to the original string), or generating an array where each position is the value of a byte?– bfavaretto
I want to revert to flip the byte array again after having turned string @bfavaretto
– Vinícius Lara
Would that be reply?
– Silvio Andorinha
i tried that, but it didn’t turn the array the same as it was.. @Silvioandorinha
– Vinícius Lara
Sorry, try again. there was an error in the code at the point and comma.
– Silvio Andorinha
@Silvioandorinha yes, but it turns an array if letters and not numbers.. make the test
– Vinícius Lara
I still don’t understand, you want to reverse operations
charCodeAt
,char >>> 8
andchar & 0xFF
or not?– bfavaretto
You want it to be "sopt test" again or you want it in numbers in array format?
– Silvio Andorinha
@bfavaretto see the example I mounted here: http://jsfiddle.net/g2a9LfyL/ I want it to be like the first one again.. see the difference using split.
– Vinícius Lara
You want to get an array like this:
['t', 'e', 's', 't', 'e', ' ', 's', 'o', 'P', 'T']
? If so, it is not possible, because its function discards information. If it is only to transform"0,116,0,101,0,115,0,116,0,101,0,32,0,115,0,111,0,80,0,84"
in an array with these numbers, just usesplit
as in the answer below and as in your own jsfiddle (it works).– bfavaretto
@bfavaretto the first impression of the console results in an array of numbers.. the second results in that array in string form and the third results in an array of numbers in string form, I want them to become an array of numbers and not numbers in string form, if you observe they are up to ""
– Vinícius Lara
Okay, I got it.. Now I get what you want, take a look at the answer.
– Silvio Andorinha
Ah, sorry, I hadn’t noticed. I also posted an answer.
– bfavaretto