串口开发,数据类型转换——字符串转 byte[],byte[]转二进制,二进制转十进制转byte[],byte[]转十进制,byte[]拼接,校验

 bytez转String

/**
 * 字节数组转换成对应的16进制表示的字符串
 *
 * @param src
 * @return
 */
public static String bytes2HexStr(byte[] src) {
    StringBuilder builder = new StringBuilder();
    if (src == null || src.length <= 0) {
        return "";
    }
    char[] buffer = new char[2];
    for (int i = 0; i < src.length; i++) {
        buffer[0] = Character.forDigit((src[i] >>> 4) & 0x0F, 16);
        buffer[1] = Character.forDigit(src[i] & 0x0F, 16);
        builder.append(buffer);
    }
    return builder.toString().toUpperCase();
}

/**
 * 十六进制字节数组转字符串
 *
 * @param src    目标数组
 * @param dec    起始位置
 * @param length 长度
 * @return
 */
public static String bytes2HexStr(byte[] src, int dec, int length) {
    byte[] temp = new byte[length];
    System.arraycopy(src, dec, temp, 0, length);
    return bytes2HexStr(temp);
}
BMSID = new String(bytes2, StandardCharsets.US_ASCII).trim();

字符串转 byte[]——含中文

/**
 * 字符串转byte数组
 * @param str
 * @return
 */
public static byte[] strTobytes(String str){
    byte[] b=null,data=null;
    try{
        b = str.getBytes("utf-8");
        //data = new String(b,"utf-8").getBytes("gbk");
        data = new String(b,"utf-8").getBytes("gb2312");
    }catch (UnsupportedEncodingException e){
        e.printStackTrace();
    }
    return data;
}

 

字符串命令转 byte[]——不含中文

/**
 * 把十六进制表示的字节数组字符串,转换成十六进制字节数组
 *
 * @param
 * @return byte[]
 */
public static byte[] hexStr2bytes(String hex) {
    int len = (hex.length() / 2);
    byte[] result = new byte[len];
    char[] achar = hex.toUpperCase().toCharArray();
    for (int i = 0; i < len; i++) {
        int pos = i * 2;
        result[i] = (byte) (hexChar2byte(achar[pos]) << 4 | hexChar2byte(achar[pos + 1]));
    }
    return result;
}

String与byte转换

String s = "这是一段中文字符串";
byte[] b = new byte[0];
try {
    b = s.getBytes("UTF-8");
    String n = new String(b,"UTF-8");
    LgqLogutil.e(".......==="+n);
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();

 byte[]转二进制0010100

public static String convertToBinaryString(byte[] data) {
    LogPlus.e("###data len   -> " + data.length);
    StringBuilder sb = new StringBuilder();
    for (int i = 0, n = data.length; i < n; ++i) {
        String bin = Integer.toBinaryString(data[i] & 0xFF);

        StringBuilder binaryStr = new StringBuilder();
        final int zeroPaddingLen = 8 - bin.length();
        for (int j = 0; j < zeroPaddingLen; ++j) {
            binaryStr.append("0");
        }
        binaryStr.append(bin);
        sb.append(binaryStr);
    }
    return sb.toString();
}

二进制转十进制转byte[]

 

byte[] dataN = new byte[4];
int[] allLed = new int[32];
int value = Integer.parseInt(convertToBinnaryStr(allLed), 2);
byte[] lengthBytes = ByteUtil.int2Bytes(value, 4);
private String convertToBinnaryStr(int[] allLed) {
    StringBuilder sb = new StringBuilder();
    for (int b : allLed) {
        sb.append(b);
    }
    return sb.toString();
}
public static byte[] int2Bytes(int v, int len) {
    byte[] bytes = new byte[len];
    for (int i = 0; i < len; i++) {
        // 高位在前
        bytes[i] = (byte) ((v >>> (len - i - 1) * 8) & 0xff);
    }
    return bytes;
}

 

 byte[]转十进制

public static int byteToInt(byte[] b) {
    int mask = 0xff;
    int temp;
    int n = 0;
    for (int i = 0; i < b.length; i++) {
        n <<= 8;
        temp = b[i] & mask;
        n |= temp;
    }
    return n;
}

byte[]拼接方法

 

byte[] dataN = new byte[6];
byte[] lengthBytes = ByteUtil.int2Bytes(liushui, 4);
System.arraycopy(lengthBytes, 0, dataN, 0, lengthBytes.length);
byte[] buyNumBytes = ByteUtil.int2Bytes(num, 1);
byte[] huodaohaoBytes = ByteUtil.int2Bytes(goodsWayId, 1);
System.arraycopy(huodaohaoBytes, 0, dataN, 4, 1);
System.arraycopy(buyNumBytes, 0, dataN, 5, 1);
setDataN(dataN);

 校验

/**
 * 异或校验和
 *
 * @param bytes
 * @param offset
 * @param len
 * @return
 */
public static byte getXOR(byte[] bytes, int offset, int len) {
    // 计算校验和 
    byte toDiff = 0;
    // 校验和为除开校验位外的所有数据做异或
    for (int i = 0; i < len; i++) {
        toDiff = (byte) (toDiff ^ bytes[i + offset]);
    }
    return toDiff;
}
// 计算校验和
byte check = ByteUtil.getXOR(bytes, 0, bytes.length - 1);

 。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

/**
 * 总加和校验
 * @param data 十六进制字符串
 * @return 返回校验码
 */
public static String checksum(String data) {
    if (data == null || data.equals("")) {
        return "";
    }
    int total = 0;
    int len = data.length();
    int num = 0;
    while (num < len) {
        String s = data.substring(num, num + 2);
        System.out.println(s);
        total += Integer.parseInt(s, 16);
        num = num + 2;
    }
    /**
     * 用256求余最大是255,即16进制的FF
     */
    int mod = total % 256;
    String hex =String.format("%02X", mod);
    return hex;
}
String jiaoyuan = checksum("85"+datas);

 ----------------------------------------------------------------------------

public static byte[] getXOR(byte[] bytes, int len) {
    byte[] partBytes = new byte[len];
    System.arraycopy(bytes,0,partBytes,0,partBytes.length);
    //LogPlus.e("###hex:" + ByteUtil.bytes2HexStr(partBytes));
    final short POLYNOMIAL = 0x1021;
    final int INITIAL_REMAINDER = 0xA1EC;
    final int TOPBIT = 1 << (16 - 1);
    int remainder = INITIAL_REMAINDER;
    for (int ibyte = 0; ibyte < len; ++ibyte) {
        remainder ^= ((partBytes[ibyte]) << (16 - 8));

        for (int i = 8; i > 0; --i) {
            if ((remainder & TOPBIT) != 0) {
                remainder = (remainder << 1) ^ POLYNOMIAL;
            } else {
                remainder = (remainder << 1);
            }
        }
    }
    byte[] crcBytes = new byte[2];
    return ByteUtil.long2bytes(remainder, crcBytes, 0, 2);

}
// 计算校验和
byte check = ByteUtil.getXOR(bytes, 0, bytes.length - 1);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值