BinaryReader is buggy and no longer maintained. Check out jDataView for an up to date version.

With WebGL coming in, it is important to be able to deal with binary data files like the models. Since there is no such thing on the internet right now I decided to make my own. The javascript BinaryReader library tries to mimic the C# BinaryReader.

The code is mostly based on the binary-parser class from Jonas Raoni Soares Silva. I've added the position management and re-factored the code to remove the with syntax.

In order to load a file into a string, you have to add req.overrideMimeType('text/plain; charset=x-user-defined'); in the Ajax XMLHttpRequest. To read more about this technique, see the Mozilla Developer Center. Here is an overview of the compatible browsers.

  • Chrome Works
  • Firefox 3.5.7: Works
  • Safari 4.0.4: Works
  • Internet Explorer 8: Does not work. Doesn't have the overrideMimeType method.
  • Opera 10.10: Does not work. Have the overrideMimeType method but doesn't take it in account.

I hope this will help you to parse binary files!

BinaryReader is buggy and no longer maintained. Check out jDataView for an up to date version.




  • new BinaryReader(data: String) - Create a BinaryReader with the specified file.

Read Methods

  • BinaryReader.readChar()
  • BinaryReader.readString(length: Number)
  • BinaryReader.readInt8()
  • BinaryReader.readUInt8()
  • BinaryReader.readInt16()
  • BinaryReader.readUInt16()
  • BinaryReader.readInt32()
  • BinaryReader.readUInt32()
  • BinaryReader.readUInt32()
  • BinaryReader.readFloat()
  • BinaryReader.readDouble()

Position Methods

  • Number) - Go to a specific position (in Byte) in the file
  • BinaryReader.getPosition() - Returns the actual position (in Byte) in the file
  • BinaryReader.getSize() - Returns the size (in Byte) of the file


  • Error("Index out of bound") - When you try to read something that is beyond the end of the file.
BinaryReader is buggy and no longer maintained. Check out jDataView for an up to date version.

Example - Demo

// Code from
function load_binary_resource(url) {
	var req = new XMLHttpRequest();'GET', url, false);
	// The following line says we want to receive data as Binary and not as Unicode
	req.overrideMimeType('text/plain; charset=x-user-defined');
	if (req.status != 200) return '';
	return req.responseText;
// Load the file
var file = load_binary_resource('author.gif');
// Create the Binary Reader
var reader = new BinaryReader(file);
// Read some informations
var tag		= reader.readString(6);
var width	= reader.readUInt16();
var height	= reader.readUInt16();
// Move around the file and try to read what is there'FA', 16));
var random	= reader.readFloat();
	tag,	// GIF89a
	width,	// 16
	height,	// 16
	random	// 66.01171875
If you liked this article, you might be interested in my Twitter feed as well.
  • Daniel

    thanks. awesome class. is there a possibility to re-encode a string to utf-8? i read a file containing a lot of binary data and also utf-8 strings which i want to display on a website encoded in utf-8

  • Vjeux

    utf8 encoding can easily be done with 2 functions:

    function encode_utf8( s )
      return unescape( encodeURIComponent( s ) );
    function decode_utf8( s )
      return decodeURIComponent( escape( s ) );


  • Daniel

    Seems not to work for my file. In my file i got those bytes: 4a 61 72 69 20 4d 61 65 6e 70 e4 e4 which reads Jari Maenpää. (e4 = ä). But i got it work using this code:

    readStringInternal : function(length) {
        var text = "";
        for(var i = 0; i < length; i++)
            text += String.fromCharCode(this.readByte());
        return text;
    readByte:   function() {
        var data = this._buffer.charCodeAt(this._pos) & 0xFF;
        return data;
  • Mathieu ‘p01′ Henri

    FYI, Opera 10.5x supports overrideMimeType('text/plain; charset=x-user-defined'); and allows to read binary data

  • anon

    I don't know why, but reading floating points (at least doubles) is broken. It seems to work changing this line at _decodeFloat:

    var curByte = length + (-precisionBits < < 3) - 1;


    var curByte = 0;
  • Pingback: Terry Butler » HTML5 Quake II MD2 Model Loader and Renderer

  • Pingback: GuruLinks : Javascript 로 SWF,PDF,SHP,NES 등 Binary 데이터 읽어서 사용하기 | Guru's Blog

  • Tlahoda

    I think there might be a bug in the _checkSize function. It checks against < this._buffer.length which fails for me when I have a double at the end of the file (I have not tried it for other types). A simple fix for this seems to be to modify the _checkSize function to check against <= this._buffer.length

  • Tlahoda

    Works in Opera 11.10

  • Tlahoda

    Could you add an endianness swapping function along the lines of the following for binary data that has the edianness swapped.

    function endianSwap (num) {
    //The shift then mask at the end prevents a sign error.
    return ((num & 0xFF) << 24) | ((num & 0xFF00) <> 8 ) | ((num >> 24) >> 0xFF);

  • Vjeux

    This lib is no longer supported. I moved all the code into jDataView:

    checkSize has been fixed and there is proper support for endianness

  • Tlahoda


  • Sandeeppster

    I have a Binary File which I created using BinaryWriter from C# and is compressed using DeflateStream. The original file is a XML file.
    When I try to read the Binary file in Javascript, the realtive ASCII value is not same. I am posting a portion of the file to make myself more clear.

    First line of XML File :

    First line of Binary File (from a Hex viewer) :
    00001001 00000101 00000000 00000000 11101101 10111101 00000111 01100000 00011100 01001001 10010110 00100101

    I am not sure if Binary file needs to decoded before using it. I have tried using decodeURIComponent, but this works on URI components only.

    Please suggest how can we use the binary file.

  • Vjeux .

    Hey Sandeeppster,

    You should check out jDataView, BinaryReader is no longer maintained and has bugs that won't be fixed.

    Demo (Show Source):

  • Arrsathish

    This code is support for IE9?

  • Eric T.

    MERCI ENORMEMENT IL ME MANQUAIT req.overrideMimeType('text/plain; charset=x-user-defined');

    Ca fait des jours que je cherche à savoir pourquoi les valeurs de mon header etaient partiellement correct! Avec cette ligne je recupere les bonnes valeurs.

    Merci beaucoup!

  • Pingback: Why doesn’t this BinaryReader in JavaScript work similarly to the C# BinaryReader? | Ask TechwikiHow

  • Pingback: Flash AS3 – URLLoader cant load binary data from different domain | Yeo Answers


Related Posts

  • April 5, 2012 Climb – Property-based dispatch in functional languages (1)
    ELS Presentation | A Generic and Dynamic Approach to Image Processing | Chaining Operators & Component Trees | Property-based dispatch in functional languages This is the third (and last) presentation about my work on Climb at the LRDE. During the first one I tackled genericity on data s...
  • August 29, 2011 Javascript: Improve Cache Performance: Reduce Lookups (2)
    In my Binary Decision Diagram Library, the performance bottleneck was the uniqueness cache. By reducing the number of cache lookup, it is possible to greatly improve the performances. Common pattern In order to test if the key is already in the cache, the usual pattern is to use key in cache....
  • June 8, 2012 CSS – Absolute position taking into account padding (5)
    When looking at the code of I remarked that they are not using top and left in order to position their images but margin-top and margin-left. I've been wondering why for some time and finally found the reason. It is a way to position absolutely elements in a container and preservi...
  • September 11, 2011 WebGL – Julia 3D Representation (0)
    At school we've been studying Lie Algebra and we were asked to make a 3D representation of a Lie Group. We chose to represent Julia Set in the Quaternion domain. We were really impressed to see that it was possible to generate many different forms given such a simple equation. Feel...
  • October 5, 2011 Javascript Presentation (1)
    The talk is over. Check out the Slides & Video. For several months now I've been surveying my friends and teachers at EPITA and I came to the conclusion that they have absolutly no idea what Javascript really is. In order to help them discover a language that is getting a lot of traction n...