How to get a binary size of a String(for example String s = "Ababa") in BITS(not bytes).
2 Answers
In what encoding? The number of bits of a particular binary representation of a string is just the number of bytes * 8:
byte[] bytes = text.getBytes("UTF-8"); // Or whatever encoding you want
int bits = bytes.length * 8;
I don't think I've ever seen an encoding which allows fractions of a byte.
Note that if you're interested in UTF-16, you can just use text.length() * 16 as each char is a UTF-16 code unit.
8 Comments
get bytes, mutiply by 8...
"xxx".getBytes().length * 8;
Edit: merging with the answer of Jon Skeet, it's could be also important to specify the encoding, otherwise this will return the size using the system's default encoding, and that's not necessarily what you want to know. To know the size using a certain encoding, use:
"xxx".getBytes(encoding).length * 8;
encoding being "UTF-8", "ASCII", or whatever you want to use.