车载canBUS开发:java各基本数据类型的字节位运算

时间:2022-10-17 17:24:36

一:首先要知道的java八大基本数据类型所占据的字节大小:
Int: 4 字节
Short: 2字节
Long: 8字节
Byte: 1字节
Character: 2字节
Float: 4字节
Double: 8字节
Boolean:系统没有提供Size方法;
输出代码如下:

private static void calSize() {
        System.out.println("Integer: " + Integer.SIZE / 8); // 4
        System.out.println("Short: " + Short.SIZE / 8); // 2
        System.out.println("Long: " + Long.SIZE / 8); // 8
        System.out.println("Byte: " + Byte.SIZE / 8); // 1
        System.out.println("Character: " + Character.SIZE / 8); // 2
        System.out.println("Float: " + Float.SIZE / 8); // 4
        System.out.println("Double: " + Double.SIZE / 8); // 8
        System.out.println("Boolean: " + Boolean.toString(false));
    }

运行结果显示:console 输出
Integer: 4
Short: 2
Long: 8
Byte: 1
Character: 2
Float: 4
Double: 8
Boolean: false

二:位运算相关代码:

public class Bit {
    public final static int Bit0 = 1<<0;
    public final static int Bit1 = 1<<1;
    public final static int Bit2 = 1<<2;
    public final static int Bit3 = 1<<3;
    public final static int Bit4 = 1<<4;
    public final static int Bit5 = 1<<5;
    public final static int Bit6 = 1<<6;
    public final static int Bit7 = 1<<7;
    public final static int Bit8 = 1<<8;
    public final static int Bit9 = 1<<9;
    public final static int Bit10 = 1<<10;
    public final static int Bit11 = 1<<11;
    public final static int Bit12 = 1<<12;
    public final static int Bit13 = 1<<13;
    public final static int Bit14 = 1<<14;
    public final static int Bit15 = 1<<15;
    public final static int Bit16 = 1<<16;
    public final static int Bit17 = 1<<17;
    public final static int Bit18 = 1<<18;
    public final static int Bit19 = 1<<19;
    public final static int Bit20 = 1<<20;
    public final static int Bit21 = 1<<21;
    public final static int Bit22 = 1<<22;
    public final static int Bit23 = 1<<23;
    public final static int Bit24 = 1<<24;
    public final static int Bit25 = 1<<25;
    public final static int Bit26 = 1<<26;
    public final static int Bit27 = 1<<27;
    public final static int Bit28 = 1<<28;
    public final static int Bit29 = 1<<29;


    public static void setBit(int src, int bit){
        src = src | bit;
    }

    public static void clrBit(int src, int bit){
        src = src & (~ bit);
    }
}

取字节的某几位,示例代码如下:

// 整车控制器LIFE,0~255循环计数,每次+1
            int sn = CanHepler.toInt(buf[0]);
            // 整车故障等级, 00:无故障, 01:一级(严重故障,立即停车), 10:二级(普通故障,限速运行),
            // 11:三级(报警故障,报警)
            int  byte1Bit01 = (CanHepler.toInt(buf[1]) & (Bit.Bit0 | Bit.Bit1));
            // 电机控制器故障等级, 00:无故障, 01:一级(严重故障,立即停车), 10:二级(普通故障,限速运行),
            // 11:三级(报警故障,报警)
            int byte1Bit23 = (CanHepler.toInt(buf[1]) & (Bit.Bit2 | Bit.Bit3)) >> 2;
            // 电池管理系统故障等级, 00:无故障, 01:一级(严重故障,立即停车), 10:二级(普通故障,限速运行),
            // 11:三级(报警故障,报警)
            int byte1Bit45 = (CanHepler.toInt(buf[1]) & (Bit.Bit4 | Bit.Bit5)) >> 4;
            // 整车控制器故障等级, 00:无故障, 01:一级(严重故障,立即停车), 10:二级(普通故障,限速运行),
            // 11:三级(报警故障,报警)
            int byte1Bit67 = (CanHepler.toInt(buf[1]) & (Bit.Bit6 | Bit.Bit7)) >> 6;// 00110011

取字节的某一位,示例代码如下:

// 动力电池单体电压过低, 0:正常, 1:故障
            int byte4Bit0 = (CanHepler.toInt(buf[4]) & (Bit.Bit0));
            // 电机控制器过温, 0:正常, 1:故障
            int byte4Bit1 = (CanHepler.toInt(buf[4]) & (Bit.Bit1)) >> 1;
            // 真空泵故障, 0:正常, 1:故障
            int byte4Bit2 = (CanHepler.toInt(buf[4]) & (Bit.Bit2)) >> 2;
            // 蓄电池电压过低(10.9V~11.9V), 0:正常, 1:故障
            int byte4Bit3 = (CanHepler.toInt(buf[4]) & (Bit.Bit3)) >> 3;
            // 电机控制器掉线, 0:正常, 1:故障
            int byte4Bit4 = (CanHepler.toInt(buf[4]) & (Bit.Bit4)) >> 4;
            // 电池管理系统掉线, 0:正常, 1:故障
            int byte4Bit5 = (CanHepler.toInt(buf[4]) & (Bit.Bit5)) >> 5;
            // SOC较低故障(10%-20%), 0:正常, 1:故障
            int byte4Bit6 = (CanHepler.toInt(buf[4]) & (Bit.Bit6)) >> 6;
            // SOC过低故障(小于10%), 0:正常, 1:故障
            int byte4Bit7 = (CanHepler.toInt(buf[4]) & (Bit.Bit7)) >> 7;

CanHepler.java文件:

    public static int toInt(byte b) {
        int result = ((int) b) & 0xff;
        return result;
    }

数据转换工具类,示例代码如下:

/** *数据转换工具 */
public class Utility {
    //-------------------------------------------------------
    // 判断奇数或偶数,位运算,最后一位是1则为奇数,为0是偶数
    static public int isOdd(int num)
    {
        return num & 0x1;
    }
    //-------------------------------------------------------
    static public int HexToInt(String inHex)//Hex字符串转int
    {
        return Integer.parseInt(inHex, 16);
    }
    //-------------------------------------------------------
    static public byte HexToByte(String inHex)//Hex字符串转byte
    {
        return (byte)Integer.parseInt(inHex,16);
    }
    //-------------------------------------------------------
    static public String Byte2Hex(Byte inByte)//1字节转2个Hex字符
    {
        return String.format("%02x", inByte).toUpperCase();
    }
    //-------------------------------------------------------
    static public String ByteArrToHex(byte[] inBytArr)//字节数组转转hex字符串
    {
        StringBuilder strBuilder=new StringBuilder();
        int j=inBytArr.length;
        for (int i = 0; i < j; i++)
        {
            strBuilder.append(Byte2Hex(inBytArr[i]));
            strBuilder.append(" ");
        }
        return strBuilder.toString(); 
    }
  //-------------------------------------------------------
    static public String ByteArrToHex(byte[] inBytArr,int offset,int byteCount)//字节数组转转hex字符串,可选长度
    {
        StringBuilder strBuilder=new StringBuilder();
        int j=byteCount;
        for (int i = offset; i < j; i++)
        {
            strBuilder.append(Byte2Hex(inBytArr[i]));
            strBuilder.append(" ");
        }
        return strBuilder.toString();
    }
    //-------------------------------------------------------
    //转hex字符串转字节数组
    static public byte[] HexToByteArr(String inHex)//hex字符串转字节数组
    {
        int hexlen = inHex.length();
        byte[] result;
        if (isOdd(hexlen)==1)
        {//奇数
            hexlen++;
            result = new byte[(hexlen/2)];
            inHex="0"+inHex;
        }else {//偶数
            result = new byte[(hexlen/2)];
        }
        int j=0;
        for (int i = 0; i < hexlen; i+=2)
        {
            result[j]=HexToByte(inHex.substring(i,i+2));
            j++;
        }
        return result; 
    }

    //-------------------------------------------------------
    static public String ByteArrToString(byte[] inBytArr)//字节数组转转ascii字符串
    {
        StringBuilder strBuilder=new StringBuilder();
        int j=inBytArr.length;
        for (int i = 0; i < j; i++)
        {
            strBuilder.append((char)(inBytArr[i]));
        }
        return strBuilder.toString(); 
    }

    //根据高低位字节码生成字符
    static public char MakeWord(byte loByte, byte hiByte) {
        int loB = (loByte & 0xFF);
        int hiB = (hiByte & 0xFF);
        int a = (0xFFFF & (loB | hiB << 8));
        return (char)(0xFFFF & (loB | hiB << 8));
    }

    //取字符的低位字节码
    static public byte LoByte(char word){
        return (byte)word;
    }

    //取字符的高位字节码
    static public byte HiByte(char word){
        return (byte)((word >> 8) & 0xFF);
    }

    public static int byteToInt(byte b){
        return (0xFF & b);
    }

/** * unicode转换成中文 * * @param unicode * @return */
    public static String unicodeToCn(byte[] unicode) {
        String returnStr = "";
        if (unicode != null && unicode.length % 2 == 0) {
            for (int i = 0; i < unicode.length / 2; i++) {
                String str = Integer.toHexString(unicode[i * 2]);
                if (str.length() > 2) {
                    str = str.substring(str.length() - 2);
                } else if (str.length() < 2) {
                    str = "0" + str;
                }

                String str2 = Integer.toHexString(unicode[i * 2 + 1]);
                if (str2.length() > 2) {
                    str2 = str2.substring(str2.length() - 2);
                } else if (str2.length() < 2) {
                    str2 = "0" + str2;
                }
                returnStr += "\\u" + str + str2;
            }

            String[] strs = returnStr.split("\\\\u");
            returnStr = "";
            for (int i = 1; i < strs.length; i++) {
                returnStr += (char) Integer.valueOf(strs[i], 16).intValue();
            }
        }
        return returnStr;
    }

    /** * 中文转换成unicode * * @param cn * @return */
    public static byte[] cnToUnicode(String cn) {
        if (cn != null) {
            char[] chars = cn.toCharArray();
            byte[] datas = new byte[chars.length * 2];
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < chars.length; i++) {
                String hexString = Integer.toHexString(chars[i]);
                sb.append(hexString + " ");
                if (hexString.length() == 0) {
                    hexString = "0000" + hexString;
                } else if (hexString.length() == 1) {
                    hexString = "000" + hexString;
                } else if (hexString.length() == 2) {
                    hexString = "00" + hexString;
                } else if (hexString.length() == 3) {
                    hexString = "0" + hexString;
                }
                String info = hexString.substring(0, 2);
                datas[i * 2] = (byte) Integer.parseInt(info, 16);
                info = hexString.substring(2, 4);
                datas[i * 2 + 1] = (byte) Integer.parseInt(info, 16);
            }
            return datas;
        } else {
            return null;
        }
    }

/** * 取出一个byte的begin到end位的数值 * * @param b * @param begin 从0开始 * @param end * @return */
    public static byte getData(byte b, int begin, int end) {
        int byteNum = 1;
        byte dataTemp = 1;

        for (int i = 1; i < (byteNum + (end - begin)); i++) {
            dataTemp = (byte) (dataTemp | (1 << i));
        }

        byte temp = (byte) (b >> begin);
        return (byte) (temp & dataTemp);
    }
/** * 截取byte数组,根据开始位置和结束位置 * * @param value * @param start * @param end * @return */
    public static byte[] splitByteArray(byte[] value, int start, int end) {
        byte[] bytes = new byte[end - start + 1];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = value[start + i];
        }
        return bytes;
    }

}