Android 16进制byte数组和16进制String,String之间转换

下面是从网上找的代码但是其中《16进制字符串转字节数组》有BUG无法转换0~15,下面有方法

/*16进制byte数组转String*/
public static String bytes2HexString(byte[] b) {
       String r = "";

       for (int i = 0; i < b.length; i++) {
           String hex = Integer.toHexString(b[i] & 0xFF);
           if (hex.length() == 1) {
               hex = '0' + hex;
           }
           r += hex.toUpperCase();
       }

       return r;
   }

/*
 * 16进制字符串转字节数组
 */
 public static byte[] hexString2Bytes(String hex) {

     if ((hex == null) || (hex.equals(""))){
         return null;
     }
     else if (hex.length()%2 != 0){
         return null;
     }
     else{
         hex = hex.toUpperCase();
         int len = hex.length()/2;
         byte[] b = new byte[len];
         char[] hc = hex.toCharArray();
         for (int i=0; i<len; i++){
             int p=2*i;
             b[i] = (byte) (charToByte(hc[p]) << 4 | charToByte(hc[p+1]));
         }
         return b;
     }

 }
/*
 * 字符转换为字节
 */
private static byte charToByte(char c) {
    return (byte) "0123456789ABCDEF".indexOf(c);
}

方法如下

/*String转byte数组*/
public static byte[] Stringtobytes(String s) {
    byte[] present = {};
    if (Integer.parseInt(s) >= 16) {
        present = hexString2Bytes(Integer.toHexString(Integer.parseInt(s)));
    }else if(Integer.parseInt(s) == 0){
        present = new byte[]{0x00};
    }else if(Integer.parseInt(s) == 1){
        present = new byte[]{0x01};
    }else if(Integer.parseInt(s) == 2){
        present = new byte[]{0x02};
    }else if(Integer.parseInt(s) == 3){
        present = new byte[]{0x03};
    }else if(Integer.parseInt(s) == 4){
        present = new byte[]{0x04};
    }else if(Integer.parseInt(s) == 5){
        present = new byte[]{0x05};
    }else if(Integer.parseInt(s) == 6){
        present = new byte[]{0x06};
    }else if(Integer.parseInt(s) == 7){
        present = new byte[]{0x07};
    }else if(Integer.parseInt(s) == 8){
        present = new byte[]{0x08};
    }else if(Integer.parseInt(s) == 9){
        present = new byte[]{0x09};
    }else if(Integer.parseInt(s) == 10){
        present = new byte[]{0x0a};
    }else if(Integer.parseInt(s) == 11){
        present = new byte[]{0x0b};
    }else if(Integer.parseInt(s) == 12){
        present = new byte[]{0x0c};
    }else if(Integer.parseInt(s) == 13){
        present = new byte[]{0x0d};
    }else if(Integer.parseInt(s) == 14){
        present = new byte[]{0x0e};
    }else if(Integer.parseInt(s) == 15){
        present = new byte[]{0x0f};
    }

    return present;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值