What does it mean if binary data is “4 byte single format” and how do I read it in JavaScript?

末鹿安然 提交于 2019-12-13 21:36:48

问题


I have to read a binary file which is said to be encoded 4 byte single format and never having to work with binary data, I don't know what this means.

I can do this reading a file with binary data in JavaScript:

 d = new FileReader();
 d.onload = function (e) {
   var i, len;
   // grab a "chunk"
   response_buffer = e.target.result.slice(0, 1024);
   view = new DataView(response_buffer);

   for (i = 0, len = response_buffer.byteLength; i < len; i += 1) {
      // hmhm
      console.log(view.getUint8(i));
   }
}
d.readAsArrayBuffer(some_file);

Which runs a loop from 0 to 1023 and I am getting numbers on the console, but I don't know if this is my decoded data :-)

Question:
What is 4 byte single format and how do I access the data correctly? What is the difference between say getUint8() and getint8() or getInt32() in "human understandable language"?

Thanks!


回答1:


4 byte single format is not a commonly understood term in computer science.

If you could expect your file to be a series of single precision floating point numbers, then I might guess that "4 byte single format" means single precision floating point because each of those is four bytes long.

You will want to use getFloat32() to parse single precision floating point numbers from the binary stream.


If you want 1024 numbers parsed with getFloat32(), then you need 1024*4 bytes and you need to advance your for loop by four bytes each time since getFloat32() processes four bytes at a time:

d = new FileReader();
 d.onload = function (e) {
   var i, len;
   // grab a "chunk"
   response_buffer = e.target.result.slice(0, 1024 * 4);
   view = new DataView(response_buffer);

   for (i = 0, len = response_buffer.byteLength; i < len; i += 4) {
      // hmhm
      console.log(view.getFloat32(i));
   }
}
d.readAsArrayBuffer(some_file);

Also, please note that IE10 and IOS 5 do not have the .slice() method for an ArrayBuffer if you're planning on using this in a general web page.



来源:https://stackoverflow.com/questions/23844960/what-does-it-mean-if-binary-data-is-4-byte-single-format-and-how-do-i-read-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!