• Post Reply Bookmark Topic Watch Topic
  • New Topic

Converted Char Array to Byte Array - lengths don't match  RSS feed

 
Bill Smyth
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have some code which converts from a char array to a byte array (without creating any intermediate Strings and that's a requirement) and I'm ending up with some extra bytes at the end. Here is some test code which illustrates the problem:



And here is the output running on jdk160_24 on Winodows:



The extra byte that results from converting from a char array using the Charset is zero valued. As the input string gets longer, the number of zero bytes appended to the end of the byte array grows. I expect that this has something to do with encoding but it seems to be that I'm specifying UTF-8 both places so I don't know why that would be.

If anyone could explain to me what's going on or otherwise point me in the right direction, I'd really appreciate it. Thanks in advance.
 
Maxim Karvonen
Ranch Hand
Posts: 121
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Bill.

You are getting a "backing array" of the ByteBuffer. It may be larger than real amount of written data. It is done to lessen number of reallocations during writing. Look at arrayOffset, capacity, position and remaining methods in ByteBuffer class.

And charset encoder usually allocates additional bytes prior to encoding. Reason is the same - to prevent future reallocation of byte-buffer (for direct buffer realocations are tricky in some way).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!