Home > Back-end >  Java String coding analytical problems
Java String coding analytical problems

Time:10-12

Run into a problem of a weird, byte array format hexadecimal number, if converted to String type, through type String get to byte array format, find that the original data will change, but also and source byte array of data is relevant, the code is as follows, if the bytes in the getBytes are {0 XFB (byte), (byte) 0 x0a}, then perform after printing is 8431 a4370a, if bytes are {0 XFB (byte), (byte) 0 x4a}, FB4A execution is printed after the original data, consult!

 
Import the Java. IO. UnsupportedEncodingException;
Import the Java. Util. Base64;

Public class MainApp {

Private static String hexToString (byte [] hexs) {
If (hexs==null | | hexs. Length & lt;=0) {
return null;
}

StringBuilder sb=new StringBuilder();
For (byte hex: hexs) {
Int ch=(int) ((hex & amp; 0 xf0) & gt;> 4);
String s=Integer. ToHexString (ch);
Sb. Append (s);

Ch=(int) (hex & amp; 0 x0f);
S=Integer. ToHexString (ch);
Sb. Append (s);
}

Return sb. ToString (). ToUpperCase ();
}
Private static byte [] getBytes () {
Byte [] bytes={0 XFB (byte), (byte) 0 x4a};
Return bytes;
}
Public static void main (String [] args) throws UnsupportedEncodingException {
String STR=new String (getBytes (), "GB18030");
System. The out. Println (hexToString (STR) getBytes (" GB18030 ")));
}
}
  • Related