Skip to content

Instantly share code, notes, and snippets.

@kapadia
Created October 26, 2012 01:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kapadia/3956486 to your computer and use it in GitHub Desktop.
Save kapadia/3956486 to your computer and use it in GitHub Desktop.
Endianness in JavaScript
// Endian Differences When Interpreting Binary Data in JavaScript
// Let's make a request for a binary file
var xhr = new XMLHttpRequest();
xhr.open('GET', 'data/m101.fits');
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
var buffer = xhr.response;
// I'll store some parameters since I know this file well.
var width = 893;
var height = 891;
// Image data exists at the byte offset of 14400
var begin = 14400;
// The (16 bit integer) image data ends at ...
var end = begin + 2 * width * height;
// Take a slice of those bytes from the array buffer
var imgBuffer = buffer.slice(begin, end);
// Initialize a typed array using the buffer (this should give me the pixel values)
var img1 = new Uint16Array(imgBuffer);
// Okay, now let's do it another way
// Create a view using the DataView object
var view = new DataView(imgBuffer);
// Store the number of pixels
var pixels = width * height;
// Initialize a typed array of length pixels
var img2 = new Uint16Array(pixels);
// Loop through calling the DataView method getInt16 on the buffer for each pixel.
for (var i = 0; i < pixels; i += 1) {
img2[i] = view.getInt16(2 * i);
}
// I expected img1 and img2 to be the same, but that's not the case.
// Initializing the typed array using the array buffer interprets the data
// as little endian, whereas using the DataView object reads the data as big endian.
// Is this difference intentional? Why have this endian mismatch?
};
xhr.send();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment