Common methods for data conversion when Android operates Bluetooth Ble

1. When operating the Bluetooth module, Android writes data according to the protocol, and the data written is hexadecimal, and the data returned by Bluetooth is also hexadecimal. Here we have to transform the data.

2. The following are methods commonly used in work, written as a tool class, which can be used directly. All tested and valid

public class CommonUtil {

    /*
     * Convert time to timestamp
     */
    public static String dateToStamp(String s) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }

    /**
     * Merge byte arrays
     */
    public static byte[] unitByteArray(byte[] byte1,byte[] byte2){
        byte[] unitByte = new byte[byte1.length + byte2.length];
        System.arraycopy(byte1, 0, unitByte, 0, byte1.length);
        System.arraycopy(byte2, 0, unitByte, byte1.length, byte2.length);
        return unitByte;
    }
    /*
      * Convert hexadecimal string to byte array
      */
    public static byte[] hexString2Bytes(String hex) {

        if ((hex == null) || (hex.equals(""))){
            return null;
        }
        else if (hex.length()%2 != 0){
            return null;
        }
        else{
            hex = hex.toUpperCase();
            int len = hex.length()/2;
            byte[] b = new byte[len];
            char[] hc = hex.toCharArray();
            for (int i=0; i<len; i++){
                int p=2*i;
                b[i] = (byte) (charToByte(hc[p]) << 4 | charToByte(hc[p+1]));
            }
            return b;
        }

    }

    /*
 * Convert characters to bytes
 */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }


    /**
     * Get the day of the week that the current date is<br>
     *
     * @param dt
     * @return The day of the week the current date is
     */
    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"07", "01", "02", "03", "04", "05", "06"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    /**
     * Convert string to hexadecimal value
     * @param bin String The string we see to be converted into hexadecimal
     * @return
     */
    public static String bin2hex(String bin) {
        char[] digital = "0123456789ABCDEF".toCharArray();
        StringBuffer sb = new StringBuffer("");
        byte[] bs = bin.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(digital[bit]);
            bit = bs[i] & 0x0f;
            sb.append(digital[bit]);
        }
        return sb.toString();
    }

    /**
     * Convert hexadecimal string into byte array
     * @param hexString
     * @return
     */
    public static byte[] toByteArray(String hexString) {

        if (TextUtils.isEmpty(hexString))
            throw new IllegalArgumentException("this hexString must not be 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 hexadecimal, it will only occupy up to 4 bits. Converting it to bytes requires two hexadecimal characters, with the high-end first

            byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);

            byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);

            byteArray[i] = (byte) (high << 4 | low);

            k += 2;
        }
        return byteArray;
    }


    /**
     * Convert byte array to hexadecimal string. The main purpose of this method is to facilitate Log display.
     */
    public String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (byte aSrc : src) {
            int v = aSrc & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv.toUpperCase()).append(" ");
        }
        return stringBuilder.toString();
    }
}

3. The above are the basic commonly used methods, just call them directly.  

Guess you like

Origin blog.csdn.net/beautifulYuan/article/details/91491844