Common Data conversion methods (Summary) for communication between Android and single chip microcomputer ),
Paste the code below
1. Convert GB2312 to Chinese, such as BAFAC2DCB2B7 → carrot, and combine two bytes into one text.
public static String stringToGbk(String string) throws Exception { byte[] bytes = new byte[string.length() / 2]; for (int j = 0; j < bytes.length; j++) { byte high = Byte.parseByte(string.substring(j * 2, j * 2 + 1), 16); byte low = Byte.parseByte(string.substring(j * 2 + 1, j * 2 + 2), 16); bytes[j] = (byte) (high << 4 | low); } String result = new String(bytes, "GBK"); return result; }
2. Convert Chinese characters to GB2312 and return results in byte [] format, such as carrot → new byte [] {ba fa C2 DC B2 B7}. One word is divided into two bytes.
public static byte[] gbkToString(String str) throws Exception { return new String(str.getBytes("GBK"), "gb2312").getBytes("gb2312"); }
3. Convert the hex byte [] to a string, such as byte [] {0x7e, 0x80, 0x11, 0x20} → 7e801120, which can be used for log printing.
public static String bytesToHexString(byte[] src) { StringBuilder stringBuilder = new StringBuilder(""); if (src == null || src.length <= 0) { return null; } for (int i = 0; i < src.length; i++) { int v = src[i] & 0xFF; String hv = Integer.toHexString(v); if (hv.length() < 2) { stringBuilder.append(0); } stringBuilder.append(hv); } return stringBuilder.toString(); }
4. convert a hex byte [] to a string without any change, and separate each byte with spaces, such as byte [] {0x7e, 0x80, 0x11, 0x20} → 7e 80 11 20, which can be used for log Printing
public static StringBuilder byte2HexStr(byte[] data) { if (data != null && data.length > 0) { StringBuilder stringBuilder = new StringBuilder(data.length); for (byte byteChar : data) { stringBuilder.append(String.format("%02X ", byteChar)); } return stringBuilder; } return null; }
5. convert byte [] arrays to 8, 10, 16, and other hexadecimal formats, such as byte [0x11, 0x20] → 4384, approximately equal to 1120 (hexadecimal) → 4384, radix stands for hexadecimal
Public static String bytesToAllHex (byte [] bytes, int radix) {return new BigInteger (1, bytes). toString (radix); // here 1 represents a positive number}
6. Convert the String hexadecimal format to byte hexadecimal format, for example, 7e20 → new byte [] {0x7e, x20}
public static byte[] HexString2Bytes(String src) { byte[] ret = new byte[src.length() / 2]; byte[] tmp = src.getBytes(); for (int i = 0; i < tmp.length / 2; i++) { ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]); } return ret; }
public static byte uniteBytes(byte src0, byte src1) { byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 })) .byteValue(); _b0 = (byte) (_b0 << 4); byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 })) .byteValue(); byte ret = (byte) (_b0 ^ _b1); return ret; }