Skip to content

Instantly share code, notes, and snippets.

@nphyx
Created September 14, 2015 06:25
Show Gist options
  • Save nphyx/5c19ef4cdb9774d87e0d to your computer and use it in GitHub Desktop.
Save nphyx/5c19ef4cdb9774d87e0d to your computer and use it in GitHub Desktop.
Accessors for unsigned 24-bit ints on Javascript DataViews
/**
* Provide a 24 bit int implementation for DataViews. Note this
* causes two reads/writes per call, meaning it's going to be
* around half as fast as the native implementations.
*/
DataView.prototype.getUint24 = function(pos) {
return (this.getUint16(pos) << 8) + this.getUint8(pos+2);
}
DataView.prototype.setUint24 = function(pos, val) {
this.setUint16(pos, val >> 8);
this.setUint8(pos+2, val & ~4294967040); // this "magic number" masks off the first 16 bits
}
@nphyx
Copy link
Author

nphyx commented Jul 1, 2021

That looks correct but it's been a while since I've messed with dataviews so I'm a little rusty. Can you confirm that it works?

@chrisveness
Copy link

It's working fine for big-endian (once defaults are included) – I've not been able to test little-endian I'm afraid, I just thought I'd offer it out :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment