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 : ).
-
See [Isn't the size of character in Java 2 bytes?](http://stackoverflow.com/questions/5078314/isnt-the-size-of-character-in-java-2-bytes) – Arne Jul 06 '12 at 18:27
-
Explanation, since OP doesn't care to give one: he wants the integer that is the string length (in bits) encoded into a stream of 64 bits, big-endian. – Marko Topolnik Jul 06 '12 at 18:57
-
I gave all the explanation. I want size of one String in the 64bits format. for example 010 this is 2 bits but in 3 bit format. – Yoda Jul 07 '12 at 11:52
3 Answers
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?
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
.
It might help if we knew what you're actually trying to do.

- 191,574
- 25
- 345
- 413
-
-
OP is obviously pushing a string into a bit stream. He needs to encode its length (in bits) into a 64-bit big-endian integer (again accessible as a bit stream), and then he'll send the string itself as a bitstream (that was his earlier question). – Marko Topolnik Jul 06 '12 at 18:59
Java works internally always using BigEndian order even if the platform like x86 uses LittleEndian.
In Java 64bit values are stored in the long
data type.
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, ...).
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:
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:
DataOutputStream out = new DataOutputStream(streamToWriteTo);
out.writeLong(charCount);

- 39,162
- 17
- 99
- 152