Skip to content

Instantly share code, notes, and snippets.

@gliese1337
Created June 21, 2011 05:06
Show Gist options
  • Save gliese1337/1037278 to your computer and use it in GitHub Desktop.
Save gliese1337/1037278 to your computer and use it in GitHub Desktop.
A simple implementation of the DataView ArrayBuffer wrapper.
var DataView = (function(){
var littleEndian = (
(new Uint16Array((new Uint8Array([0x12, 0x34])).buffer)[0] === 0x3412)
?true:false); //Determine native endianness
function dv(buffer){
this.buffer = buffer;
this.bytes = new Uint8Array(buffer);
}
dv.prototype = {
getU8 : function(offset) {
return this.bytes[offset];
},
getI8 : function(offset) {
return this.bytes[offset] - 1<<7;
},
getU16 : function(offset, le) {
if(le==littleEndian){ //if desired endianness matches native endianness
return (new Uint16Array(this.buffer,offset,2))[0];
}
return (le //otherwise, do the expansion 'by hand'
?(this.bytes[offset+1] << 8) | this.bytes[offset]
:(this.bytes[offset] << 8) | this.bytes[offset+1]
);
},
getI16 : function(offset, le) {
if(le==littleEndian){
return (new Int16Array(this.buffer,offset,2))[0];
}
return (le
?(this.bytes[offset+1] << 8) | this.bytes[offset]
:(this.bytes[offset] << 8) | this.bytes[offset+1]
) - 1<<15;
},
getU32 : function(offset, le) {
if(le==littleEndian){
return (new Uint32Array(this.buffer,offset,4))[0];
}
return (le
?(this.bytes[offset+3] << 24) | (this.bytes[offset+2] << 16) | (this.bytes[offset+1] << 8) | this.bytes[offset]
:(this.bytes[offset] << 24) | (this.bytes[offset+1] << 16) | (this.bytes[offset+2] << 8) | this.bytes[offset+3]
);
},
getI32 : function(offset, le) {
if(le==littleEndian){
return (new Int32Array(this.buffer,offset,4))[0];
}
return (le
?(this.bytes[offset+3] << 24) | (this.bytes[offset+2] << 16) | (this.bytes[offset+1] << 8) | this.bytes[offset]
:(this.bytes[offset] << 24) | (this.bytes[offset+1] << 16) | (this.bytes[offset+2] << 8) | this.bytes[offset+3]
) - 1<<31;
}
};
return dv;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment