How to count the number of bits of a text using java

Asked

Viewed 236 times

-1

I’m making a particular app, I literally scoured the internet and I couldn’t find a way to count the number of bits of a particular phrase, someone can help me.

2 answers

3


You just need to know the number of bytes and multiply by 8. For example:

System.out.println("teste".getBytes().length * 8); //40
  • 1

    What if the text is encoded in utf-8? There may be characters that occupy more than 8 bits.

  • 4

    Anderson, so the "getBytes()" and not the String size directly.

  • 1

    In fact, my fault.

1

Knowing that each sentence character has 8 bits just do this:

String str = "Algum texto";
int numDeBits = str.length * 8;

I don’t know if this is the java syntax but anything leaves a comment that I try to fix.

  • 3

    What if the text is encoded in utf-8? There may be characters that occupy more than 8 bits.

  • 1

    in case will occupy 9 dai ne?

  • 2

    accented characters can increase the size of bytes in a string, even with the same number of characters, so it is best to count the number of bytes in the string.

  • 1

    ah then the answer from below is correct.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.