Convert string to array of integers and vice versa in JavaScript -
i have array, each cell of can keep 4 bytes (2**32). array presents memory of vm write in js. have string. 1 place can keep string - memory describe above.
i decided present strings in memory c-strings (with special symbol nul end of string). current implementation looks ugly , asking advice, there way improve approach? maybe there other way it?
part of code, converts string array:
// demomemory presents memory model var demo_volume = 16; var demomemory = new array(demo_volume); (var = 0; < demo_volume; i++) demomemory[i] = 0; // convert string hexidecimal string var string = "hello, world!", hexstring = ""; (var = 0; < string.length; i++) { hexstring += string.charcodeat(i).tostring(16); } // convert hexidecimal string array of strings // each element of array presents 4 symbols var hexstringarray = hexstring.match(/.{1,8}/g); // add nul (0x00) symbols complete strings while (hexstringarray[hexstringarray.length - 1].length != 8) { hexstringarray[hexstringarray.length - 1] += "00"; } // convert integer array (var = 0; < hexstringarray.length; i++) { demomemory[i] = parseint(hexstringarray[i], 16); }
...and string:
// decode string var resultstring = "", decsymbolcode = 0; (var = 0; < demomemory.length; i++) { hexstring = demomemory[i].tostring(16); var hexsymbolcodearray = hexstring.match(/.{1,2}/g); (var j = 0; j < hexsymbolcodearray.length; j++) { decsymbolcode = parseint(hexsymbolcodearray[j], 16); resultstring += string.fromcharcode(decsymbolcode); } }
this code inappreciable because i'm using js strings build hexadecimal strings. think possible bitwise operations , masks, don't know, how. maybe i'm wrong.
here code converts string array of 32bit numbers , vice versa using masks , bitwise operations:
var demomemory = []; function stringtoarray(str) { var i, length = str.length, arr = []; for(i=0; i<length; i+=4) { arr.push( (((str.charcodeat(i) || 0) << 24) |((str.charcodeat(i+1) || 0) << 16) |((str.charcodeat(i+2) || 0) << 8) |((str.charcodeat(i+3) || 0))) ); } if(length % 4 === 0) { arr.push(0); } return arr; } function arraytostring(arr) { var i, j, chrcode, length = arr.length, str = []; label: for(i=0; i<length; i++) { for(j=24; j>=0; j-=8) { chrcode = (arr[i] >> j) & 0xff; if(chrcode) { str.push(string.fromcharcode(chrcode)); } else { break label; } } } return str.join(''); } console.log(demomemory = stringtoarray('hello, world!')); // => [1214606444, 1865162839, 1869769828, 553648128] console.log(arraytostring(demomemory)); // "hello, world!"
working example can find here: http://jsbin.com/aselug/2/edit
Comments
Post a Comment