user5536767
user5536767

Reputation:

How do I get the binary data of a file as a string of 1s and 0s?

So, as part of a little experiment, I need to access the binary data of a file, an image for example, as a string or array of 1s and 0s.

I read the documentation on the file reader, I'm attempting to use the readAsBinaryString method but it gives me a bunch of weird characters rather than what I'd normally think a string of binary should look like. Here's my code:

function handleFiles(files){
   var selectedFile = files[0];
   var reader = new FileReader();
   reader.readAsBinaryString(selectedFile);
   reader.onloadend = function () {
      var result = reader.result;
      store(result);
   }
}

function store(data){
    console.log('Storing data...');
   console.log(data.slice(0, 1000));
}

As a web developer, I dont normally work with binary, so I'm probably fairly naive about this. Can someone explain how I get actual 1s and 0s?

Upvotes: 1

Views: 96

Answers (1)

user5536767
user5536767

Reputation:

I think I figured it out:

function handleFiles(files) {
  var selectedFile = files[0];
  var reader = new FileReader();
  reader.readAsBinaryString(selectedFile);
  reader.onloadend = function() {
    var result = reader.result;
    store(result);
  };
}

function store(data) {
  console.log("Storing data...");
  var result = '';
  data = data.slice(0, 1000)
  for (var i1 = 0; i1 < data.length; i1++) {
    result += data[i1].charCodeAt(0).toString(2) + " ";
  }
  console.log(result);
}

Upvotes: 1

Related Questions