title: Efficient way to calculate byte length of a character, depending on the encoding
body: <p>What's the most efficient way to calculate the byte length of a character, taking the character encoding into account? The encoding would be only known during runtime. In UTF-8 for example the characters have a variable byte length, so each character needs to be determined individually. As far now I've come up with this:</p>
  
  <pre><code>char c = getCharSomehow();
  String encoding = getEncodingSomehow();
  // ...
  int length = new String(new char[] { c }).getBytes(encoding).length;
  </code></pre>
  
  <p>But this is clumsy and inefficient in a loop since a <code>new String</code> needs to be created everytime. I can't find other and more efficient ways in the Java API. There's a <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#valueOf%28char%29" rel="nofollow noreferrer"><code>String#valueOf(char)</code></a>, but according its source it does basically the same as above. I imagine that this can be done with bitwise operations like bit shifting, but that's my weak point and I'm unsure how to take the encoding into account here :)</p>
  
  <p><sub><i>If you question the need for this, check <a href="https://stackoverflow.com/questions/2725897/reverse-massive-text-file-in-java/2725993#2725993">this topic</a>.</i></sub></p>
  
  <hr>
  
  <p><strong>Update:</strong> the answer from <a href="https://stackoverflow.com/questions/2726071/efficient-way-to-calculate-byte-length-of-a-character-depending-on-the-encoding/2726284#2726284">@Bkkbrad</a> is technically the most efficient:</p>
  
  <pre><code>char c = getCharSomehow();
  String encoding = getEncodingSomehow();
  CharsetEncoder encoder = Charset.forName(encoding).newEncoder();
  // ...
  int length = encoder.encode(CharBuffer.wrap(new char[] { c })).limit();
  </code></pre>
  
  <p>However as <a href="https://stackoverflow.com/users/139985/stephen-c">@Stephen C</a> pointed out, there are more problems with this. There may for example be combined/surrogate characters which needs to be taken into account as well. But that's another problem which needs to be solved in the step <em>before</em> this step.</p>