开发者

Binary data handling and bitwise AND

开发者 https://www.devze.com 2023-03-20 09:08 出处:网络
I saw this code sample without any explanation: var xhr = new XMLHttpRequest(); xhr.open(\'GET\', \'/path/to/image.png\', true);

I saw this code sample without any explanation:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/image.png', true);

// Tr开发者_开发知识库ick to pass bytes through unprocessed.
xhr.overrideMimeType('text/plain; charset=x-user-defined');

xhr.onreadystatechange = function(e) {
  if (this.readyState == 4 && this.status == 200) {
    var binStr = this.responseText;
    for (var i = 0, len = binStr.length; i < len; ++i) {
      var c = binStr.charCodeAt(i);
      //String.fromCharCode(c & 0xff)
      var byte = c & 0xff;  // byte at offset i
    }
  }
};

xhr.send();

I wonder what that line var byte = c & 0xff; // byte at offset i is doing? Why AND with 0xFF? This code is in JavaScript if that matters.


The code appears to be storing a byte value. Apparently, the developer thought it was possible that c could contain more than 8 bits (a byte) of data. By ANDing with 0xff, any data beyond 8 bits is trimmed off (or at least set to zero).

0

精彩评论

暂无评论...
验证码 换一张
取 消