2

As a personal project, I'm writing a 6502 emulator in JavaScript (HTML5 based). I'm porting some bits of it from a predecessor I created in C. To load in the files (ROMs in my case), I could use this C code:

unsigned char* buffer = calloc(1, 4096);
FILE* file = fopen("xyz", "rb");
fread(buffer, 1, 4096, file);
fclose(file);

and access it like this:

char firstChar = buffer[0];
short nextShort = (buffer[2] << 8) | buffer[1];
free(buffer);

Now, I need to be able to port this to JavaScript. For input, I can do something like this using a file input:

var file = document.getElementById("picker").files[0];
var reader = new FileReader();
reader.readAsDataURL(file);

From here, I have reader.result as a giant, base64 encoding of the file. I need a way to access the binary file as I did in the beginning C example, where I can simply get the values (or use simple bitwise operations)

I'm guessing the most feasible solution would be an array of values 0-255, but I just need access, regardless of how.

4
  • Bit manipulation is really not my thing, but I believe you should be reading the file into an ArrayBuffer with FIleReader.readAsArrayBuffer. Commented Jul 14, 2013 at 18:02
  • Yup, that did the trick, closing this. Commented Jul 14, 2013 at 18:16
  • 1
    Let me suggest you something: add your last update as an answer, and accept your own answer. This can be valuable content for future visitors! Commented Jul 14, 2013 at 18:18
  • Thanks! And you even got 15 rep points in the process! ;) Commented Jul 14, 2013 at 19:06

2 Answers 2

1

@bfavaretto pointed me in the correct direction

var file = document.getElementById("picker").files[0];
var reader = new FileReader();
reader.readAsArrayBuffer(file);
var buffer = new Uint8Array(reader.result);

Which can then be accessed as buffer[0] for the first byte.

Sign up to request clarification or add additional context in comments.

Comments

1

I'm the author of simplebuf library. It allows quick binary parsing/serialization and is purely written in javascript.

Example:

var layout = [
    sb.field("len", sb.type.uint(32)),
    sb.field("padding", sb.type.uint(32)),
    sb.field("id", sb.type.string_dynamic("len"))
];
var original = {len: 4, "padding": 999, "id": "1234"};
sb.write(buffer, 0, original, layout);

https://github.com/conceptacid/simplebuf.js

1 Comment

I would be interested by this, do you still have it somewhere?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.