Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Handling binary data in JS

Handling binary data in JS

LondonJS. TypedArray, DataView, XHR2.

Kornel Lesiński

February 18, 2013
Tweet

More Decks by Kornel Lesiński

Other Decks in Technology

Transcript

  1. TypedArray DataView arr = new Uint32Array(buf) val = arr[1] dv

    = new DataView(buf) val = dv.getUint32(4) arr2 = new Int8Array(buf) val = arr2[0] val = dv.getInt8(0)
  2. new DataView(buf) .getUint16(0) var bytes = new Uint8Array(buf) bytes[0] =

    0x13 bytes[1] = 0x37 0x3713 0x1337 new Uint16Array(buf)[0] TypedArray DataView
  3. 0x3713 0x1337 0x13,0x37 Little Endian Motorola (PowerPC) Number literals Big

    Endian Intel (x86) iOS/Android ARM Network Byte Order Host Byte Order*
  4. <input type=file> var file = input.files[0]; var reader = new

    FileReader(); reader.onload = function() { var arraybuffer = reader.result; var dv = new DataView(arraybuffer); console.log(dv.getUint32(0)); } reader.readAsArrayBuffer(file);
  5. var data = new Uint8Array(100); var blob = new Blob([data],

    {type:"application/octet-stream"}); var a = document.createElement("a"); a.download = "test.blob"; a.href = URL.createObjectURL(blob); a.click();
  6. <input type=file> var file = input.files[0]; var img = new

    Image(); img.src = URL.createObjectURL(file); document.body.appendChild(img);
  7. var blob = new Blob(["hello world"]); var form = new

    FormData(); form.append("file", blob); var xhr = new XMLHttpRequest(); xhr.open("POST", "/form"); xhr.send(form); xhr.open("PUT", "/file"); xhr.send(blob);
  8. var xhr = new XMLHttpRequest(); xhr.responseType = "arraybuffer"; xhr.onload =

    function() { var arraybuffer = this.response; } xhr.open("GET", "/file"); xhr.send();
  9. $ hexdump -C file.png 89 50 4e 47 0d 0a

    1a 0a 00 00 00 0d 49 48 44 52 |.PNG........IHDR| 00 00 06 cb 00 00 04 a2 08 03 00 00 00 c4 24 27 |..............$'| c3 00 00 00 04 67 41 4d 41 00 00 b1 8f 0b fc 61 |.....gAMA......a| 05 00 00 00 01 73 52 47 42 00 ae ce 1c e9 00 00 |.....sRGB.......| 00 c0 50 4c 54 45 0e 2e 00 10 6f e4 8b 8c df 40 |..PLTE....o....@| 43 4b 02 42 e0 b2 51 cf 63 42 21 68 0b cf c8 9b |CK.B..Q.cB!h....| 77 a1 5f 31 b9 82 5d 5c 9c bb 7f b5 d5 9e 16 00 |w._1..]\........| 31 8a ae cd af 9d 15 a2 e0 ba d2 e2 00 82 be cc |1...............|
  10. var dv = new DataView(png_arraybuffer); var offset = 8; //

    header var txt = new TextDecoder(); while(offset < dv.byteLength) { var len = dv.getUint32(offset); var chunk_id = new Uint8Array(dv.buffer, offset+4, 4); var name = txt.decode(chunk_id); console.log("Chunk", name, len); offset += 4+4+4+len; }