String str = "1134f1aaac"
怎么装换成  byte[]  bb     bb[0]=11,bb[1]=34,bb[2]=f1,bb[3]=aa,bb[4]=ac

解决方案 »

  1.   

    byte 数组 怎么能出现 字母
      

  2.   

    byte[2] = (byte)f1   这样不行吗?
      

  3.   

    String str = "1134f1aaac";
    byte[] bytes = str.getBytes();
    for (byte b : bytes) {
    System.out.println(b);
    }
      

  4.   

    每两个字符截取一次,然后强转行成byte
      

  5.   

    public class Test1{
    public static main(String[] args){
    String str = "1134f1aaac";
            byte[] bytes = str.getBytes();
            for (byte b : bytes) {
                System.out.println(b);
    }     
       }
    }
      

  6.   

    import java.util.Arrays;public class StringToBytes {
    //测试
    public static void main(String[] args) {
    String str = "1134f1aaac";
    byte[] bb = getBytesFromString(str);
    if(bb == null) {
    System.out.println("结果是null");
    }
    //直接显示结果,这样类似“aa”这样的数,都会显示为负。
    System.out.println(Arrays.toString(bb));
    //转换后显示
    for(int i = 0; i < bb.length; i++ ) {
    if(i % 8 == 0  ) {
    System.out.println();
    }
    System.out.print("bb[" + i + "] = " + StringToBytes.byteToHexString(bb[i]) + "\t");

    }
    }
    /**
     * 转换函数
     * @param s
     * @return
     */
    public static byte[] getBytesFromString(String s) {
    //s 如果为空,则返回null.
    if(null == s || s.equals("")) {
    return null;
    }

    //大写字母都换成小写。
    s = s.toLowerCase();

    //用正则表达式判断是否有非数字字符,如含有非数字字符,则返回null.
    if(!s.matches("[a-f0-9]+")) {
    System.out.println("There is other character!");
    return null;
    }

    //如果长度不是偶数,前面补零, 使长度为偶数。
    if(s.length() % 2 != 0) {
    s = "0" + s;
    } //把字符串变成字节数组,这时数组长度与字符串长度一致,里面的内容是字符的ASCII码。
    byte[] temp = s.getBytes();


    int length = temp.length;

    //定义结果字节数组,其长度是字符串长度的一半。
    byte[] result = new byte[length / 2]; //定义几个临时变量。
    byte tempByte = 0;
    byte tempHigh = 0;
    byte tempLower = 0;

    //开始转换。
    for(int i = 0, j = 0; i < length; i += 2, j++) {
    tempByte = temp[i];


    if(tempByte >= 48 && tempByte <= 57)
    {
    tempHigh = (byte)((tempByte - 48) << 4);
    }
    else if(tempByte >= 97 && tempByte <= 102)//'a'--'e' 
    {
    tempHigh = (byte)((tempByte - 97 + 10) << 4);
    }

    tempByte = temp[i + 1];
    if(tempByte >= 48 && tempByte <= 57)
    {
    tempLower = (byte)((tempByte - 48));
    }
    else if(tempByte >= 97 && tempByte <= 102)//'a'--'e' 
    {
    tempLower = (byte)((tempByte - 97 + 10));
    }

    //每次转换结果放在结果数组里面。
    result[j] = (byte)(tempHigh|tempLower);
    }
    return result;
    }

    /**
     * 把字节整数,转换成16进制字符串。
     * @param b
     * @return
     */
    public static String byteToHexString(byte b) {
    int temp = Byte.toUnsignedInt(b);
    return Integer.toHexString(temp);
    }
    }