byte conversion to char storage in JAVA

Source: Internet
Author: User

//data type conversion

The basic types in Java are all signed types. The data obtained from the file read stream is a byte array. Some of these values are ASCII values greater than 127, so that the symbol bit goes wrong when converting to a char array, and the workaround: If the value is greater than 127 (that is, less than 0), add 256 to the value, thereby correcting the sign bit. The sample code is as follows:

Gets a 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 ();

//About String.getbyte Error Resolution:

When you store ruby in string, some diacritics convert the error, and you can use the following method:

 //gets the char array from string, processed to 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.