The following code is directly affixed
1. Convert GB2312 to Chinese, such as bafac2dcb2b7→ Carrot, two bytes to synthesize one text
Public StaticString STRINGTOGBK (String string)throwsException {byte[] bytes =New byte[String.Length ()/2]; for(intj = 0; J < Bytes.length; J + +) { byteHigh = Byte.parsebyte (String.substring (J * 2, J * 2 + 1), 16); byteLow = Byte.parsebyte (String.substring (J * 2 + 1, J * 2 + 2), 16); BYTES[J]= (byte) (High << 4 |Low ); The String result=NewString (Bytes, "GBK"); returnresult; }
2. Convert Chinese to GB2312, and results returned in byte[] form, such as Carrot →new byte[]{ba FA C2 DC B2 B7}, a word is divided into two bytes
Public Static byte throws Exception { returnnew String (str.getbytes ("GBK"), "gb2312"). GetBytes ("gb2312" ); }
3. Convert the hexadecimal byte[] intact to a string, such as byte[]{0x7e,0x80,0x11,0x20}→7e801120, for log printing
Public StaticString bytestohexstring (byte[] src) {StringBuilder StringBuilder=NewStringBuilder (""); if(src = =NULL|| Src.length <= 0) { return NULL; } for(inti = 0; i < src.length; i++) { intv = src[i] & 0xFF; String HV=integer.tohexstring (v); if(Hv.length () < 2) {stringbuilder.append (0); } stringbuilder.append (HV); } returnstringbuilder.tostring (); }
4. Convert the hexadecimal byte[] intact to a string and separate each byte with a space, such as byte[]{0x7e,0x80,0x11,0x20}→7e 80 11 20, which can be used for log printing
Public StaticStringBuilder Byte2hexstr (byte[] data) { if(Data! =NULL&& data.length > 0) {StringBuilder StringBuilder=NewStringBuilder (data.length); for(bytebytechar:data) {Stringbuilder.append (String.Format ("%02x", Bytechar)); } returnStringBuilder; } return NULL; }
5. Convert the byte[] array to 8, 10, 16, etc., such as byte[0x11,0x20]→4384, approximately equal to 1120 (16-binary) →4384,radix represents the binary
Public Static String Bytestoallhex (byteint radix) { returnnew BigInteger (1, bytes). toString (radix); // The 1 here represents a positive number }
6. Convert the hexadecimal of a string to hexadecimal of byte, for example 7e20→new byte[]{0x7e,x20}
Public Static byte [] hexstring2bytes (String src) { bytenewbyte[Src.length ()/2]; byte [] tmp = src.getbytes (); for (int i = 0; i < TMP.LENGTH/2; i++) { = unitebytes (Tmp[i * 2], Tmp[i * 2 + 1]); } return ret; }
Common data conversion method for Android and MCU Communication (summary)