title: Reading a UTF-8 String from a ByteBuffer where the length is an unsigned int
body: <p>I am trying to read a UTF8 string via a java.nio.ByteBuffer.  The size is an unsinged int, which, of course, Java doesn't have.  I have read the value into a long so that I have the value.</p>
  
  <p>The next issue I have is that I cannot create an array of bytes with the long, and casting he long back to an int will cause it to be signed.</p>
  
  <p>I also tried using limit() on the buffer, but again it works with int not long.</p>
  
  <p>The specific thing I am doing is reading the UTF8 strings out of a class file, so the buffer has more in it that just the UTF8 string.</p>
  
  <p>Any ideas on how to read a UTF8 string that has a potential length of an unsigned int from a ByteBuffer.</p>
  
  <p>EDIT: </p>
  
  <p><a href="http://java.sun.com/j2se/1.4.2/docs/guide/jpda/SourceDebugExtension_attribute.html" rel="nofollow noreferrer">Here is an example of the issue</a>.</p>
  
  <pre><code>SourceDebugExtension_attribute {
         u2 attribute_name_index;
         u4 attribute_length;
         u1 debug_extension[attribute_length];
      }
  
  attribute_name_index
      The value of the attribute_name_index item must be a valid index into the constant_pool table. The constant_pool entry at that index must be a CONSTANT_Utf8_info structure representing the string "SourceDebugExtension".
  
  attribute_length
      The value of the attribute_length item indicates the length of the attribute, excluding the initial six bytes. The value of the attribute_length item is thus the number of bytes in the debug_extension[] item.
  
  debug_extension[]
      The debug_extension array holds a string, which must be in UTF-8 format. There is no terminating zero byte.
  
      The string in the debug_extension item will be interpreted as extended debugging information. The content of this string has no semantic effect on the Java Virtual Machine.
  </code></pre>
  
  <p>So, from a technical point of view, it is possible to have a string in the class file that is the full u4 (unsigned, 4 bytes) in length. </p>
  
  <p>These won't be an issue if there is a limit to the size of a UTF8 string (I am no UTF8 expert so perhaps there is such a limit).</p>
  
  <p>I could just punt on it and go with the reality that there is not going to be a String that long... </p>