Transferred from: http://blog.csdn.net/linlzk/article/details/6566124
Java and other languages written programs for TCP/IP socket communication, the communication content is generally converted to a byte array type, Java in the character and array conversion is also very convenient;
1. Convert character to byte array
String str = "Luo long";
byte[] sb = Str.getbytes ();
2. Converting a byte array into characters
Byte[] b={(byte) 0xb8, (Byte) 0xDF, (Byte) 0xCB, (byte) 0xd9};
String str= new string (b);
3, in order to facilitate the addition and subtraction of characters, usually with 16 binary characters instead of ordinary characters and byte arrays to convert each other
/**
* 16 binary string representation to byte array
*
* @param hexstring
* 16 strings in binary format
* @return the converted byte array
**/
public static byte[] Tobytearray (String hexstring) {
if (Stringutils.isempty (hexstring))
throw new IllegalArgumentException ("This hexstring must is not being empty");
hexstring = Hexstring.tolowercase ();
Final byte[] ByteArray = new Byte[hexstring.length ()/2];
int k = 0;
for (int i = 0; i < bytearray.length; i++) {//because it is 16 binary, up to 4 bits, converted to bytes requires two 16 characters, high
byte high = (Byte) (Character.digit (Hexstring.charat (k), +) & 0xff);
byte low = (byte) (Character.digit (Hexstring.charat (k + 1), & 0xff);
Bytearray[i] = (byte) (High << 4 | low);
K + = 2;
}
return byteArray;
}
/**
* byte array to 16 binary representation of the formatted string
*
* @param ByteArray
* Byte array to convert
* @return 16 binary representation of the formatted string
**/
public static String tohexstring (byte[] byteArray) {
if (ByteArray = = NULL | | Bytearray.length < 1)
throw new IllegalArgumentException ("This byteArray must is not null or empty");
Final StringBuilder hexstring = new StringBuilder ();
for (int i = 0; i < bytearray.length; i++) {
if ((Bytearray[i] & 0xff) < 0x10)//0~f front non-zero
Hexstring.append ("0");
Hexstring.append (integer.tohexstring (0xFF & Bytearray[i));
}
Return hexstring.tostring (). toLowerCase ();
}
Conversion between byte array byte[] and characters (strings) in Java