3

How to get a binary size of a String(for example String s = "Ababa") in BITS(not bytes).

1
  • 2
    It is hard to tell without knowledge about encoding. Maybe tell us more about what do you need that for? Commented Jul 7, 2012 at 14:11

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Hi Jon, aren't Java strings internally represented by two-byte characters?
@PabloSantaCruz: Yes, but that's somewhat irrelevant - or at least, it's not what the OP asked. It's a very vague question at the moment.
@RobertKilar: Actually, my answer was before lxx's (14:07:37 vs 14:08:25) - not that it really matters. Pick the better answer; a minute either way isn't important.
@Ixx: On the other hand, it uses the platform-default encoding rather than specifying one, which is almost always the wrong approach. I definitely wouldn't use that code.
@Ixx: By "you would have set some encoding" - you mean change the system default? Ick, no thanks. I'd rather be explicit every time I want to use an encoding.
|
5

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.

1 Comment

@RobertKilar If answer time of one question is 14min ago, and another 15 minutes ago which answer was earlier?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.