如何以位为单位获取大小 Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11367641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:47:33  来源:igfitidea点击:

How to get size in bits Java

javastringsizeendianness

提问by Yoda

How to get a size of String in 64 bits(not bytes)in big endian order)? I have never done this kind of operations in Java. Thanks for any help : ).

如何以大端顺序获取 64 位(不是字节)的字符串大小?我从来没有在Java中做过这种操作。谢谢你的帮助 : )。

回答by ametren

I think you want this:

我想你想要这个:

String source = "0123456789";
byte[] byteArray = source.getBytes("UTF-16BE");
int sizeInBits = byteArray.length * 8;

Source: Why does byteArray have a length of 22 instead of 20?

来源:为什么 byteArray 的长度是 22 而不是 20?

回答by Louis Wasserman

Eh? Strings can only either be measured in chars, or in bytes, and that only once you specify a specific charset for the encoding.

诶?字符串只能以字符或字节来衡量,并且只有在您为编码指定特定字符集之后。

For the latter, it's just string.getBytes(charset).length.

对于后者,它只是string.getBytes(charset).length.

It might help if we knew what you're actually trying to do.

如果我们知道您实际上想要做什么,这可能会有所帮助。

回答by Robert

Java works internally always using BigEndian order even if the platform like x86 uses LittleEndian.

即使像 x86 这样的平台使用 LittleEndian,Java 在内部也始终使用 BigEndian 顺序。

In Java 64bit values are stored in the longdata type.

在 Java 中,64 位值存储在long数据类型中。

Now the final question is what you want to measure. In a String you can count the number of characters, or the number of bytes the String takes when encoding it using a specified encoding (e.g UTF-8, UTF-16, ISO-8859-1, ...).

现在最后一个问题是你想测量什么。在字符串中,您可以计算字符串使用指定编码(例如 UTF-8、UTF-16、ISO-8859-1 等)进行编码时的字符数或字节数。

Assuming you want to count the number of characters in a String and you want to get the number as a 64bit number you can use the following code:

假设你想计算一个字符串中的字符数,并且你想得到一个 64 位的数字,你可以使用以下代码:

String myString = "abcdefgh";
long charCount = myString.length;

If you want to write charCountinto a file or into a network connection you can use DataOutputStream for getting a BigEndian representation:

如果要写入charCount文件或网络连接,可以使用 DataOutputStream 获取 BigEndian 表示:

DataOutputStream out = new DataOutputStream(streamToWriteTo);
out.writeLong(charCount);