Home > Back-end >  Java utf8 GBK, then converted into hexadecimal string data
Java utf8 GBK, then converted into hexadecimal string data

Time:10-12

GBK utf8, then the converted data into hexadecimal string, such as cold storage 12 - C0E4BFE2B7BF3132
Ask for help,

CodePudding user response:

Hint: two step do

The character set conversion of the string
The binary array of strings, the hexadecimal characters

CodePudding user response:

 
Public static String string2HexString (String STR, String charName) {
Char [] chars=0123456789 "abcdef". ToCharArray ();
The StringBuilder sb=new StringBuilder (" ");
Byte [] bs=STR. GetBytes (Charset. Class.forname ());
Int bit;
for (int i=0; I & lt; Bs. Length; I++) {
Bit=(bs [I] & amp; 0 x0f0) & gt;> 4.
Sb. Append (chars [bit]);
Bit=bs [I] & amp; 0 x0f;
Sb. Append (chars [bit]);
//sb. Append (");
}
Return sb. ToString (). The trim ();
}

Public static String Hex2String (String source, the String ) throws the Exception {
Source=source. The toUpperCase ();
Int sourceLen=source. The length ();
Char [] sourcechars=source. ToCharArray ();
String hexDigital="0123456789 abcdef";
Byte [] resultBytes=new byte (sourceLen)/2;
//3 cycle the old string in turn two into one
int n;
for (int i=0; I & lt; ResultBytes. Length; I++) {
I * n=hexDigital. IndexOf (sourcechars [2]) * 16 + hexDigital indexOf (sourcechars (2 * I + 1));

ResultBytes [I]=(byte) (n & amp; 0 XFF);
}
Return a new String (resultBytes, Charset. Class.forname ());
}

Public static void main (String [] args) throws the Exception {
String hexStr=BytesUtil. String2HexString (" cold warehouse 12 ", "GBK");
System. The out. Println (hexStr);
String oldStr=BytesUtil. Hex2String (hexStr, "GBK");
System. The out. Println (" get original value is: "+ oldStr);
}

CodePudding user response:

If the bytecode is UTF8, then need to GBK byte HEX code?
The String s=new String (utf8 bytes, "utf-8")
Byte [] b=s.g etBytes (" GBK ")
Then each byte into two HEX is ok;

CodePudding user response:

Very simple, write two common methods, transformation
  • Related