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 Sep 14, 2015

Unit test (for Mocha+Chai) is here: https://gist.github.com/nphyx/5895d07fba9686ac357f

@DanielJDufour
Copy link

Hi, @nphyx. This has been super helpful! I'm currently trying to add arbitrary 1-32 bit functionality to geotiff.js (geotiff on npm). I was wondering if getUint24 is for little endian or big endian? And if it's one of those, do you know what it would look like if there's another type of endian?

Thank you very much and have a great day. :-)

@chrisveness
Copy link

chrisveness commented Jun 29, 2021

Would this be correct to cater for both little-endian and big-endian?

DataView.prototype.getUint24 = function(byteOffset=0, littleEndian=false) {
    return littleEndian
        ? this.getUint8(byteOffset) + (this.getUint16(byteOffset+1) << 8, true)
        : (this.getUint16(byteOffset) << 8) + this.getUint8(byteOffset+2);
}

@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