2012-06-25 304 views
-2

我有一個偶數的長度的byte []數組。 現在,我希望byte []數組的前半部分的長度與byte []數組中的前兩個字節一起作爲字節b1,後兩個字節b2等等。將byte []數組轉換爲字節數

請幫忙。 謝謝

+5

你的問題真的不是很清楚,我...尤其是你想怎麼兩個字節組合成一個... –

+3

聽起來功課給我。 –

回答

0

這功課嗎?我想你的主要問題是將成對的字節組合成雙字節。這是通過什麼叫做左移(<<)實現的,該字節爲8位,所以由8個移動:

int doubleByte = b1 + (b2 << 8); 

請注意,我用b1作爲低字節,b2爲高字節。其餘的很簡單:分配一個長度爲字節數組一半長度的int的數組,然後迭代你的字節數組來構建新的int數組。希望這可以幫助。

+0

好,謝謝你們努力的朋友。例如:字節{130C00D2C00001}是我所擁有的。爲了在13,0C和00上執行一些操作,我需要將它們分開。我想你現在在哪裏清楚。 – sreekanthnu

+0

對不起,此評論不是很有幫助。 – maksimov

0

也許我理解你的問題完全錯誤。

public class Main { 
    // run this 
    public static void main(String[] args) {  

     // create the array and split it 
     Main.splitArray(new byte[10]); 
    } 

    // split the array 
    public static void splitArray(byte[] byteArray) { 
     int halfSize = 0; // holds the half of the length of the array 
     int length = byteArray.length; // get the length of the array 
     byte[] b1 = new byte[length/2]; // first half 
     byte[] b2 = new byte[length/2]; // second half 
     int index = 0; 

     if (length % 2 == 0) { // check if the array length is even 
      halfSize = length/2; // get the half length 

      while (index < halfSize) { // copy first half 
       System.out.println("Copy index " + index + " into b1's index " + index); 
       b1[index] = byteArray[index]; 
       index++; 
      } 

      int i = 0; // note the difference between "i" and "index" ! 
      while (index < length) { // copy second half 
       System.out.println("Copy index " + index + " into b2's index " + i);// note the difference between "i" and "index" ! 
       b2[i] = byteArray[index];// note the difference between "i" and "index" ! 
       index++; 
       i++; //dont forget to iterate this, too 
      } 

     } else { 
      System.out.println("Length of array is not even."); 
     } 
    } 
} 
+0

感謝您的努力,我的朋友。我得到了答案 – sreekanthnu