2012-05-09 22 views
1

我試圖將特定字符串轉換爲字節[]。將特定字符串轉換爲字節[]

的字符串看起來像: 55 55 F5 FF FF

,這裏是我寫它的方法,希望有人能告訴我什麼是錯的或有更好的解決方案。

public static byte[] stringToByte(String text) { 
    //byte[] length ==> String (length+1)/3 
    byte raw[] = new byte[(text.length() + 1)/3]; 
    int j = 0; 
    for (int i = 0; i < text.length(); i += 2) { 
     String h = ""; 
     h += text.charAt(i); 
     h += text.charAt(i + 1); 
     i++; 
     raw[j] = Byte.valueOf(h); 
     j++; 
    } 
    return raw; 
} 

問題是它的工作,直到涉及到F5。

我需要的值相同的字節[],如果我用

byte raw[] = {(byte) 0x55, (byte) 0x55, (byte) 0x5F,(byte) 0xFF,(byte) 0xFF}; 
+0

對不起,它的錯誤。當我使用「raw = text.getBytes();」我得到了一個有14個職位的數組,但我需要一個5個像我的問題中的最後一個代碼塊。 – Jay

+0

如果您查看「Byte.valueOF」的文檔,它會指向'parseByte',其中指出「字符串中的字符必須全部爲十進制數字,但第一個字符可能是ASCII減號」 。這就是爲什麼當你給它一個「F」時它會爆炸。 –

+2

哦,現在我明白了 - 我認爲這個適合:http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using -java – birryree

回答

2

這將工作:

public static byte[] stringToByte(String text) { 
    final String[] split = text.split("\\s+"); 
    final byte[] result = new byte[split.length]; 
    int i = 0; 
    for (String b : split) result[i++] = (byte)Integer.parseInt(b, 16); 
    return result; 
} 

爲什麼? byte是簽署量,您不能直接將其範圍內的任何內容解析爲byte。但是,如果你解析一個int,然後使用縮小轉換爲byte,你會得到你的結果。

0

看起來你只是通過一個空格分隔字符串循環,並解析出字節的對象。在這種情況下,我建議使用類似:

  String text = ""; 
     String[] strArr = text.split(" "); 
     for (String str: strArr) 
     { 
      //convert string to byte here 
     } 
0
byte[] raw = new byte[text.length() >> 1]; 
for(int i=0; i<text.length();i+=2){ 
    raw[i >> 1] = Integer.parseInt(text.substring(i, i+2),16); 
} 

我以前Integer.parseInt()代替Byte.parseByte()因爲字節是不是無符號字節。我嘗試了String text = "55555FFF";

+0

你的代碼產生'Type mismatch:can not convert from int to byte',但它很容易修復。 –

+0

@MarkoTopolnik oops,使用'GroovyConsole'對其進行了測試 – user845279

0

您也可以爲每個標記使用StringTokenizer

public static byte[] stringToByte(String text) { 
    StringTokenizer st = new StringTokenizer(text); 
    byte raw[] = new byte[st.countTokens()]; 
    for (int i = 0; i < raw.length; i++) { 
     raw[i] = (byte) Integer.parseInt(st.nextToken(), 16); 
    } 
    return raw; 
} 
+1

您是否測試了它? 'java.lang.NumberFormatException:值超出範圍。價值:「F5」基數:16'雖然不是一個大問題。 –

+0

我明白了。謝謝! –