Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does charCodeAt(...) & 0xff accomplish?

Tags:

javascript

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);
like image 321
Ray Avatar asked Dec 23 '13 19:12

Ray


People also ask

What is the use of charCodeAt ()?

The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.

What is Unicode in Javascript?

Unicode in Javascript source code In Javascript, the identifiers and string literals can be expressed in Unicode via a Unicode escape sequence. The general syntax is \uXXXX , where X denotes four hexadecimal digits. For example, the letter o is denoted as '\u006F' in Unicode.

What is ascii in JS?

ASCII is a numeric value that is given to different characters and symbols for computers to store and manipulate. For example, the ASCII value of the letter 'A' is 65. Resource: ASCII chart of all 127 characters in JavaScript.

How do I find the character code?

Go to Insert >Symbol > More Symbols. Find the symbol you want. Tip: The Segoe UI Symbol font has a very large collection of Unicode symbols to choose from. On the bottom right you'll see Character code and from:.


1 Answers

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.

like image 117
Scott Mermelstein Avatar answered Nov 02 '22 14:11

Scott Mermelstein