几个byte工具类

hex形式的byte 转 byte 如WORD 类型 0x277e 这时候是ascii 转int 39 *256+7e&0xFF
等于10110.根据传输的格式来进行,也可以转成String 再转回来,以下是根据理论走出的方法。(应该不是最优方法)

/**
 * ascii to byte
 */
public static byte[] asciiToByte(byte[] data, int length){
    if(length % 2 !=0){
        return null;
    }
    byte[] bytes = new byte[length/2];
    for(int i = 0,j = 0;i

Byte转String 便于打印查看报文数据是否正确

  public static String byteToHex(byte[] data){
            StringBuilder str = new StringBuilder();
        for (int i = 0; i < data.length; ++i) {
        str.append(byteToHex(data[i]));
    }
    return str.toString();
        }

public static String byteToHex(byte b){
    return String.format("%02x ", b);
}

ByteToHex 转换

    public static String byteToHex(byte b) {
          String hex = Integer.toHexString(b & 0xFF);
          if (hex.length() < 2) {
              hex = "0" + hex;
          }
          return hex;
        }

int 转word

public static byte[] getAsicc(int num){
     byte[] bytes = new byte[2];
     int a = num/256;
     int b = num - a*256;
     bytes[0] = (byte)a;
     bytes[1] = (byte)b;
     return bytes;
 }

你可能感兴趣的:(几个byte工具类)