2016-03-02 176 views
-2

我只是想弄清楚如何將int數轉換爲字節。 聽起來很簡單,但對我來說很難知道如何轉換它。如何將int轉換爲字節?

對於e.g:

public byte[] getByteArray(String ipOrMac){ 

     String[] temp = new String[0]; 
     ArrayList<Integer> intList = new ArrayList<Integer>(); 

     if(ipOrMac.contains(":")){ 
      temp = ipOrMac.split(":"); // this makes temp into a new Array 
             //with splitted strings 
     } 

     if(ipOrMac.contains(".")){ 
      temp = ipOrMac.split("."); 
     } 

     for(int a = 0; a<=temp.length-1; a++){ 
      intList.add(Integer.parseInt(temp[a])); 
     } 

//  System.out.println(stringList.toArray()[0]); 
//  for(int a = 0; a<=stringList.size()-1; a++){ 
//   stringList. 
//  } 

     return null; 
    } 

我maintarget是得到這樣的字符串 「2:2:2:2」(這是一個MAC-ADRESS) 成一個byte []。 所以現在我有問題將我的arraylist-integer中的所有整數轉換爲字節。 我不想使用arraylist字節,因爲它效率低下...

所以有什麼想法嗎?

希望你能幫助我。 :)

+0

*「我不想使用a rraylist-byte,因爲效率不高......「*程序變慢,因爲它們做了太多事情。除非你使用'List'做了一百萬次,否則沒有理由想到微型優化,更不用說設計你的程序了。 – Radiodef

+0

@Radiodef,提示強制性「過早優化是萬惡之源」。 –

回答

1

你可以試試下面的代碼片段:

String[] temp = ipOrMac.split(ipOrMac.contains(":") ? ":" : "\\."); 

byte[] array = new byte[temp.length]; 

for(int i = 0; i < temp.length; ++i) 
    array[i] = (byte)Integer.parseInt(temp[i]); 
+0

相同的解決方案,少用線。 ty – Ceeya

+0

現在我必須避免負數。 – Ceeya

+0

又是我。 String.split(「‘)無法識別。’」 ......爲什麼? – Ceeya

0

如果我理解正確...你想將字符串轉換爲字節[],對不對?

你只需要做到這一點:

的byte [] ipOrMacBytes = ipOrMac.getBytes();

+0

這不太可能完成OP想要的內容,即獲取字符串中數字的實際數值。 –

2

相反,寫

byte[] bytes = new byte[temp.length]; 
    for(int a = 0; a< temp.length; a++){ 
     bytes[a] = (byte) Integer.parseInt(temp[a]); 
    } 
    return bytes; 
+0

日本人很好。現在我必須避免0到-127的負數。 :) 謝謝! – Ceeya

+0

@Cem理解這一點很重要,不,你不知道。有這些負面字節是*正確。* –

+0

是的,但你不能在mac或ipadresse負數。 – Ceeya

1

這個怎麼樣例如:

(全碼:https://github.com/anjalshireesh/gluster-ovirt-poc/blob/master/backend/manager/modules/utils/src/test/java/org/ovirt/engine/core/utils/jwin32/AppTest.java#L153

try { 
     ByteBuffer bb = ByteBuffer.allocate(16); 
     bb.order(ByteOrder.LITTLE_ENDIAN); 

     String[] arrSidParts = strSid.split("-"); 
     for (int i = 4; i < arrSidParts.length; i++) { 
      bb.putInt((int) Long.parseLong(arrSidParts[i])); 
     } 

     Guid guid = new Guid(bb.array(), false); 
     out.println(guid.toString()); 

    } catch (Exception e) { 
     out.println("!" + e.getMessage() + "!"); 
     e.printStackTrace(); 
    } 
+0

那些ByteBuffer會自動避免負數? (從0到-127)? – Ceeya