Win a copy of Terraform in Action this week in the Cloud forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Piet Souris
  • Al Hobbs
  • salvin francis

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

Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    Bookmark Topic Watch Topic
  • New Topic