有谁知道如何计算字符串中的字节数?

发布于 2024-11-26 04:51:51 字数 394 浏览 1 评论 0原文

如果我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

憧憬巴黎街头的黎明 2024-12-03 04:51:51

嗯,如果字符串中的每个元素都是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?

慈悲佛祖 2024-12-03 04:51:51

@Charlie 所以 01000001 只是 8 位?凉爽的。你能把它变成一个
回答这样我就可以投票吗?

确切地说,请参见下文。

如果有人要求您只计算位数,您需要同时计算 0 和 1。请记住,“位”本质上是信息内容的度量。因此,如果您有一个信息内容为 16 位的字段,则意味着有 2^16 种可能的配置,而您当前的配置只是其中之一。您的位字符串是这些配置之一,但您需要零来区分是否与其他 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文