简体   繁体   English

如何以位为单位获取大小

[英]How to get size in bits Java

How to get a size of String in 64 bits(not bytes)in big endian order)? 如何以大端顺序获取64位(不是字节)的String大小? I have never done this kind of operations in Java. 我从未在Java中进行过此类操作。 Thanks for any help : ). 谢谢你的帮助 : )。

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?

Eh? Strings can only either be measured in chars, or in bytes, and that only once you specify a specific charset for the encoding. 字符串只能以char或字节为单位进行度量,并且只有在为编码指定了特定的字符集后才能进行度量。

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. 如果我们知道您实际上要做什么,可能会有所帮助。

Java works internally always using BigEndian order even if the platform like x86 uses LittleEndian. Java在内部始终使用BigEndian顺序工作,即使x86之类的平台使用LittleEndian。

In Java 64bit values are stored in the long data 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 (eg 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 charCount into 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM