Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - How to translate string and byte[] in java?
How to translate string and byte[] in java?
1. String to byte []

byte[]mid bytes = isostring . getbytes(" UTF8 ");

//encoding UTF8

byte[]ISO ret = SRT 2 . getbytes(" ISO-8859- 1 ");

//ISO-8859- 1 code.

Where ISO-8859- 1 is a single-byte code.

2.byte[] is converted into a string

String ISO String = new String(bytes," ISO-8859- 1 ");

String srt2 = new string (middle byte, "UTF-8");

Description:

In network transmission or other applications, there is often the same middleware, assuming it is a string type. Therefore, it is necessary to convert other types of data into middleware types.

When a string is transmitted on the network, such as socket, it needs to be converted into byte[] type. If different codes are used in this process, unexpected problems may occur, such as garbled codes.

Here's an example:

When we use socket to transmit string data, we often use UTF-8 encoding, which can avoid a problem of "Chinese garbled code".

From:

String sendString= "send data";

byte[] sendBytes= sendString。 getBytes(" UTF8 ");

..... socket send

Receiving end:

String recString = new string (sendBytes, "UTF-8");

However, such problems often occur here. In other words, the data you want to send is of type byte[].

If UTF-8 encoding is used to convert to middleware string type, there will be problems.

For example:

byte[] bytes = new byte[] { 50,0,- 1,28,-24 };

String sendString = new string (bytes, "UTF-8");

byte[] sendBytes= sendString。 getBytes(" UTF8 ");

Then send it.

Reverse conversion on acceptance

String recString = new string (sendBytes, "UTF-8");

byte[]my bytes = isostring . getbytes(" UTF8 ");

At this point, the data in Mybytes will be [50,0,-17, -65, -67,28,-17, -65, -67].

Therefore, it is necessary to adopt single-byte coding for conversion.

String sendString = new string (bytes, "UTF-8"); Change it to string sendstring = new string (bytes, "ISO-8859-1");

byte[]my bytes = isostring . getbytes(" UTF8 "); Change it to byte [] mybytes = isostring.getbytes ("ISO-8859-1");

In this way, the required bytes are recovered.