Guest User

Typed Array

a guest
Mar 7th, 2015
298
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. @giannino1995
  2.  
  3. Ti rispondo qui ché il forum è mezzo sfasciato…
  4.  
  5. Allora. L'inizializzazione. Ci sono due modi possibili (tieni conto che un Int32 utilizza 4 bytes):
  6.  
  7. var oBuffer = new ArrayBuffer(256);
  8. var oView32 = new Int32Array(oBuffer);
  9.  
  10. alert(oBuffer.byteLength); // 256
  11. alert(oView32.length); // 64
  12.  
  13. oppure
  14.  
  15. var oView32 = new Int32Array(64);
  16. var oBuffer = oView32.buffer;
  17.  
  18. alert(oBuffer.byteLength); // 256
  19. alert(oView32.buffer.byteLength); // 256
  20. alert(oView32.length); // 64
  21.  
  22. Io preferisco il secondo.
  23.  
  24. …Detto questo, “oView32” sarà un normale array (o quasi), le cui proprietà però potranno essere solo numeri di 32 bit (e come tali verranno convertiti nei casting). Ti faccio un paio di esempi:
  25.  
  26. var oView32 = new Int32Array(64);
  27.  
  28. oView32[0] = 97;
  29. alert(oView32[0]); // "97"
  30.  
  31. oView32[1] = 2147483647000; // (> 32 bit)
  32. alert(oView32[1]); // "-1000" (sic!)
  33.  
  34. oView32[2] = "H";
  35. alert(oView32[2]); // "0" (sic!)
  36.  
  37. oView32[3] = true;
  38. alert(oView32[3]); // "1"
  39.  
  40. // Valori non settati...
  41.  
  42. alert(oView32[4]); // "0"
  43. alert(oView32[5]); // "0"
  44.  
  45. // etc. etc.
  46.  
  47. Ancora esempio:
  48.  
  49. var sTxt = "Ciao mondo!!";
  50. var oView32 = new Int32Array(sTxt.length);
  51.  
  52. for (var nIdx = 0; nIdx < sTxt.length; nIdx++) {
  53. oView32[nIdx] = sTxt.charCodeAt(nIdx);
  54. }
  55.  
  56. alert(String.fromCharCode.apply(null, oView32)); // "Ciao mondo!!"
  57.  
  58. Finché lavori sui 32 bit la conversione in stringa è semplice. Ma occhio ché se hai a che fare con 8 bit o 16 bit diventa più complessa e devi lavorare sulle codifiche Unicode. Però per tua fortuna tempo fa scrissi questa libreria (stringview.js):
  59. https://developer.mozilla.org/en-US/Add-ons/Code_snippets/StringView
  60.  
  61. Esempio:
  62.  
  63. var oTxt = new StringView("Ciao mondo!!");
  64.  
  65. alert(oTxt); // "Ciao mondo!!"
  66.  
  67. alert(oTxt.rawData.constructor); // Uint8Array
  68. alert(String.fromCharCode.apply(null, oTxt.rawData)); // "Ciao mondo!!"
  69.  
  70. Spero di esserti stato di aiuto!
  71.  
  72. carlomarx
Advertisement
Add Comment
Please, Sign In to add comment