Byte conversion to Char storage in Java

Source: Internet
Author: User

// Data type conversion

The basic types in Java are all signed. The data obtained from the file reading stream is a byte array, and its central score is an ASCII value greater than 127. In this way, an error occurs when converting to the char array. solution: if the value is greater than 127 (that is, less than 0), add 256 to the value to correct the symbol bit. The sample code is as follows:

// Obtain the byte array from string
Int Len = Str. Length ();
Byte [] AB = new byte [Len];
AB = Str. getbytes ();
 
For (INT I = 0; I <Len; I ++)
{
If (AB [I] <0)
System. Out. Print (char) (AB [I] + 256 ));
Else
System. Out. Print (char) (AB [I]);
}
System. Out. println ();

 

// String. getbyte error solution:

When the string is used to store pinyin, some letters with tones are incorrectly converted. You can use the following method:

// Obtain the char array from string and convert it to the byte array
Char [] AC = new char [8];
Str. getchars (0, Len, AC, 0 );

Byte [] arrb = new byte [Len];
For (INT I = 0; I <Len; I ++)
{
Arrb [I] = (byte) AC [I];
If (arrb [I] <0)
System. Out. Print (char) (arrb [I] + 256 ));
Else
System. Out. Print (char) (arrb [I]);
}

Related Article

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.