美文网首页
几个byte工具类

几个byte工具类

作者: 就爱烫卷发 | 来源:发表于2019-04-19 14:47 被阅读0次

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<length-1;i = i+2,j++){
        bytes[j] = (byte)(isAscii(data[i],i)+isAscii(data[i+1],i+1));
    }
   return bytes;
}
//ascii 码转数字
public static int isAscii(byte b,int i){
    int index = b&0xFF;
   if(index-48<=9){
       index = index - 48;
   }else  if(65<=index&&index<=70){
       //
       index =  index - 65+10;
   }else if(97<=index&&index<=102){
       index =  index - 97+10;
   }
  //word 类型转分高低位
   if(i%2==0) {
       index = index * 16;
   }
   return  index ;
}

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工具类

      本文链接:https://www.haomeiwen.com/subject/jddswqtx.html