Java's new string (byte []). getbytes bytes loss Phenomenon

Source: Internet
Author: User

Although this kind of application is rare, it will not even happen, but keep a record and deepen the impact so that the cause cannot be found in the future.

See: Why
New String (bytes, ENC). getbytes (ENC) does not return the original byte array?

That is, when you cannot confirm that all bytes under the specified encoding can be recognized, do not use new string for encoding; otherwise, not only this byte is lost, even the next byte is lost.

For example

Utils. printbytes (new string (New byte [] {-35}). getbytes ());

This output will be 63, because-35 cannot be identified in the current default encoding and is converted ?, Then, the bytes are 63.

Try adding a byte later.

Utils. printbytes (new string (New byte [] {-35, 2}). getbytes ());

This output is still 63. It should be found that after-35 is unrecognizable, the dual-byte parsing will still fail, and the two bytes will be converted into one character ?, Then there is 63.

Of course, it does not mean that the first one cannot be parsed, so it must lose two bytes of information, such

Utils. printbytes (new string (New byte [] {-35,-11 }). getbytes (); system. out. println (new string (New byte [] {-35,-2 }));

At this time, the dual-byte can be parsed, and then encoded to obtain the original byte information.

If you want to convert a byte array to a string, you can convert it to hex string first, and use integer. tohexstring or base64 encoding.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.