How can i convert a four-character array to an integer?
4 Answers
You're trying to turn those characters into ASCII character codes and using the codes as byte values. This can be done using charCodeAt. For instance:
var str = "x7={";
var result = ( str.charCodeAt(0) << 24 )
+ ( str.charCodeAt(1) << 16 )
+ ( str.charCodeAt(2) << 8 )
+ ( str.charCodeAt(3) );
This returns 2016886139 as expected.
However, bear in mind that unlike C++, JavaScript will not necessarily use a one-byte, 256-character set. For instance, '€'.charCodeAt(0) returns 8364, well beyond the maximum of 256 that your equivalent C++ program would allow. As such, any character outside the 0-255 range will cause the above code to behave erraticaly.
Using Unicode, you can represent the above as "砷㵻" instead.
2 Comments
var arr = [5,2,4,0],
foo = +arr.join('');
console.log(foo, typeof foo);
1 Comment
I guess that depends on how you want to map the character values to the integer's bits.
One straight-forward solution would be:
var myArray = ['1', '2', '3', '4']
var myInt = (myArray[0].charCodeAt(0) << 24) | (myArray[1].charCodeAt(0) << 16) | (myArray[2].charCodeAt(0) << 8) | myArray[3].charCodeAt(0);
This produces the integer 0x01020304. This uses integers in the input array, for characters the result might be different depending on the characters used.
Update: use charCodeAt() to convert characters to code points.
2 Comments
<<, so any character outside [0-9] would be treated as zero.
[0]or at[3]? Also: what base?