fctom1215
2020-02-14 806ed6836b84fbea87d19a0cb4414e120dd9c049
app/src/main/java/safeluck/drive/evaluation/util/Utils.java
@@ -1,7 +1,11 @@
package safeluck.drive.evaluation.util;
import android.content.res.Resources;
import android.util.Log;
import android.util.TypedValue;
import com.anyun.exam.lib.MyLog;
import com.anyun.exam.lib.util.ByteUtil;
/**
 * MyApplication2
@@ -10,6 +14,7 @@
 * All Rights Saved! Chongqing AnYun Tech co. LTD
 */
public class Utils {
    private static final String TAG = "Utils";
    public static float px2dp(float value){
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,value, Resources.getSystem().getDisplayMetrics());
    }
@@ -22,4 +27,73 @@
    public static float dp2Px(int dpValue){
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX,dpValue,Resources.getSystem().getDisplayMetrics());
    }
    /**
     * 平台协议生成的校验码
     * @param bytes
     * @return
     */
    public static byte calCheckCode(byte[] bytes){
        byte checkCode =0;
        // 参与运算的两个值,如果两个相应bit位相同,则结果为0,否则为1。
        for (int i = 0; i < bytes.length; i++) {
            checkCode ^= bytes[i];
        }
        return checkCode;
    }
    /**
     * 转义
     * 采用Ox7e表示,若校验码、消息头以及消息体中出现0x7e,则要进行转义处理,转义规则定义如下:
     * 0x7e<——>0x7d后紧跟一个0x02;
     * 0x7d<——>0x7d后紧跟一个0x01。
     * @param datas
     * @return
     */
    public static byte[] transferMeaning(byte[] datas){
        byte [] temp = new byte[datas.length*2];
        int y = 0;
        temp[y++] = 0x7e;
        for (int i = 1; i < datas.length-1; i++) {
            if (datas[i] == 0x7E) {
                temp[y++] = 0x7D;
                temp[y++] = 0x02;
            } else if (datas[i] == 0x7D) {
                temp[y++] = 0x7D;
                temp[y++] = 0x01;
            } else {
                temp[y++] = datas[i];
            }
        }
        temp[y++] = 0x7e;
        Log.i(TAG,"转义过后:"+ ByteUtil.byte2hex(temp));
        return temp;
    }
    /**
     *接收消息时:转义还原
     * @param datas
     * @return
     */
    public static byte[] parseMsg(byte[] datas){
        byte[] temp = new byte[datas.length];
        int y =0 ;
        for (int i = 0; i < datas.length; i++) {
            if (datas[i]==0x7d && datas[i+1]==0x02 ){
                temp[y++] = 0x7e;
                i++;
                continue;
            }else if (datas[i]==0x7d && datas[i+1]==0x01 ){
                temp[y++] = 0x7d;
                i++;
                continue;
            }else{
                temp[y++] = datas[i];
            }
        }
        return temp;
    }
}