有谁知道如何计算字符串中的字节数?
如果我在 JavaScript 中有一个字符串,那么计算该字符串占用的字节数或位数的最佳方法是什么?
我的第一个想法是,由于 EcmaScript 规范 (5.1) 在 8.4 中声明 EcmaScript 中的字符串元素由 16 位值组成,并且这些语言使用 UTF-16 字符编码,因此我应该获得该值的十进制表示形式 (charCodeAt),将其除以二,将结果取底,鲍勃就是你父亲的兄弟。
但是,如果我要将每个字符转换为二进制 (toString(2)),为了计算位数,我是否会计算 0 和 1?还是只是1?
根据我在网上阅读的内容(信息很少),我认为它是这样的:
Math.floor("A".charCodeAt(0) / 2); // 32 bits... No?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯,如果字符串中的每个元素都是16位,那么字符串所占的位数不就是string.length * 16吗?
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?
确切地说,请参见下文。
如果有人要求您只计算位数,您需要同时计算 0 和 1。请记住,“位”本质上是信息内容的度量。因此,如果您有一个信息内容为 16 位的字段,则意味着有 2^16 种可能的配置,而您当前的配置只是其中之一。您的位字符串是这些配置之一,但您需要零来区分是否与其他 16 位配置。 ——查理·马丁昨天
我不知道,老实说。我用谷歌搜索了一些,我不断得到教如何打开计算机的东西,你显然已经掌握了这些东西。您可以尝试像计算机科学家一样思考。
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
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.