What does charCodeAt(…) & 0xff accomplish?

后端 未结 1 1268
攒了一身酷
攒了一身酷 2021-02-15 01:22

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.



        
1条回答
  •  臣服心动
    2021-02-15 02:04

    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.

    0 讨论(0)
提交回复
热议问题