开发者

Does anyone know how to count the number of bytes in a string?

If I have a string in JavaScript what's the best way to go about counting the number of bytes or bits the string takes up?

My first thought is that, since the EcmaScript spec (5.1) states in 8.4 that string elements in EcmaScript consist of 16 bits values, and that the languages uses UTF-16 character encoding, I should get the Decimal开发者_如何转开发 representation of that (charCodeAt), divide that by two, floor the result, and Bob's your father's brother.

But if I were to convert each character to binary (toString(2)), in order to count the bits, do I count the 0's as well as the 1's? Or just the 1's?

From what I've read online (and the information is sparse), I'm thinking it's something like:

Math.floor("A".charCodeAt(0) / 2); // 32 bits... No?


Um, if each element in the string is 16 bits, won't the number of bits the string takes up just be string.length * 16?


@Charlie So 01000001 is simply 8 bits? Cool. Can you turn this into an answer so I can up vote it?

Exactly, see below.

You need to count both the 0's and 1's if someone asks you just to count the bits. Remember that "bit" is at heart a measure of information content. SO if you have a field that has an information content of 16 bits, that means there are 2^16 possible configurations, of which your current configuration is just one. Your bit string is one of those configurations, but you need the zeros to tell if from other configurations with 16 bits. – Charlie Martin yesterday

also, do you know of any good books on this? I'm self taught (until uni next year). :) – Tom yesterday

I don't, honestly. I googled some, and I keep getting things that teach how to turn on the computer, something you've clearly already mastered. You might try Think like a Computer Scientist.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜