Reputation: 1788
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.
Upvotes: 2
Views: 735
Reputation: 338
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
Upvotes: 0
Reputation: 1788
@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.
Upvotes: 1