Reputation: 103
i'm not sure what 0xFF does here... is it there just to make sure that the binary code is 8bit long or has something to do with the signed/unsigned encoding? ty.
var nBytes = data.length, ui8Data = new Uint8Array(nBytes);
for (var nIdx = 0; nIdx < nBytes; nIdx++) {
ui8Data[nIdx] = data.charCodeAt(nIdx) & 0xff;
}
XHR.send(ui8Data);
Upvotes: 10
Views: 5129
Reputation: 15397
You're right with your first guess. It takes only the least significant 8 bits of what's returned by data.charCodeAt.
charCodeAt
will return a value in the range of 0..65536. This code truncates that range to 0..255. Effectively, it's taking each 16-bit character in the string, assuming it can fit into 8 bits, and throwing out the upper byte.
[6 years later edit] In the comments, we discovered a few things: you're questioning the code for the MDN polyfill for sendAsBinary. As you came to understand, the least significant byte does come first in little-endian systems, while the most significant byte comes first in big-endian systems.
Given that this is code from MDN, the code certainly does what was intended - by using FileReader.readAsBinaryString
, it stores 8bit values into a 16bit holder. If you're worried about data loss, you can tweak the polyfill to extract the other byte using sData.charCodeAt(nIdx) && 0xff00 >> 8
.
Upvotes: 10