Package com. zdz8207.test;
/**
* Convert a Chinese character string to a hex byte array. One Chinese character is saved in two bytes, and a large integer is saved in two bytes.
* @ Author zhengdunzhuang
*
*/
Public class chinesecharacterstringtobytearray {
Public static void main (string [] ARGs ){
Byte [] DATA = new byte [42];
Data [0] = (byte) 0x04;
Data [1] = (byte) (42 );
Printhexstring (data );
System. Out. println ("");
String MSG = "you have successfully added Mr. Li as a friend ";
Data = tohexbytebystrings (data, 3, MSG );
Printhexstring (data );
/*
* Result required for conversion using tools:
You have added Mr. Li as a friend.
{0x4f60, 0x5df2, 0x6210, 0x529f, 0x6dfb, 0x52a0, 0x674e, 0x5148, 0x751f, 0x4e3a, 0x597d, 0x5 3cb, 0x0 };
Print the output result:
042a000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Bytes
4f60
*/
Int I = 20320; // 0x4f60
Byte [] B = inttobytearray (I );
System. Out. println ("");
Printhexstring (B );
}
// Convert an integer to a byte array
Public static byte [] inttobytearray (int I ){
Byte [] result = new byte [2];
Result [0] = (byte) (I & 0xff00)> 8 );
Result [1] = (byte) (I & 0xff );
Return result;
}
/*** Convert the Chinese character string to hexadecimal encoding and put it into the byte array. One character and two byte bytes * @ Param Data byte array * @ Param start indicates the start number to be appended, start = 4 * @ Param s string * @ return */
Public static byte [] tohexbytebystrings (byte [] data, int start, string s ){
Int J = start;
For (INT I = 0; I <S. Length (); I ++ ){
Int CH = (INT) S. charat (I );
Data [J-1] = (byte) (ch & 0xff00)> 8 );
Data [J] = (byte) (ch & 0xff );
J + = 2;
}
Return data;
}
// Convert the string to a hexadecimal encoded string
Public static string tohexbystrings (string s ){
String STR = "";
For (INT I = 0; I <S. Length (); I ++ ){
Int CH = (INT) S. charat (I );
String S4 = integer. tohexstring (CH );
STR = STR + S4;
}
Return STR; // 0x indicates hexadecimal
}
// Print the hexadecimal string
Public static void printhexstring (byte [] B ){
For (INT I = 0; I <B. length; I ++ ){
String hex = integer. tohexstring (B [I] & 0xff );
If (Hex. Length () = 1 ){
Hex = '0' + hex;
}
System. Out. Print (Hex. touppercase ());
}
}
}