2013-09-30 57 views
0

我們有一個隨機數和隨機數的數組,例如。按二進制數組選擇數組

[12, 2345, 232, 52, 24]. 

而我們只想選擇那些由二進制數字定義的例如。

5= 101 = [0, 0, 1, 0, 1] 

所以陣列X,我想是

[0, 0, 232, 0, 24]; 

int[] x = {12, 2345, 232, 52, 24}; 
int b = 5; 
int[] X = eliminate(x, b); 

// 
x = [12, 2345, 232, 52, 24] 
b = [ 0, 0, 1, 0, 1] 
X = [ 0, 0, 232, 0, 24] 

任何快速的方法來做到這一點?

感謝

+2

順便說一句,3不是'101'但'11','101'將5 – Thomas

+0

@Thomas我糾正說,它似乎是一個錯字。 –

+0

@Mazmart我不確定你是否需要int - > bitarray轉換,所以我在我的答案中加入了一個。 –

回答

3

使用BitSet也許會有幫助,爲intBitSet之間的轉換看看這裏:BitSet to and from integer/long

下面是使用來自鏈接Bits類快速劈:

public static int[] eliminate(int[] x, int b) { 
    BitSet bs = Bits.convert(b); 
    int[] X = new int[x.length]; 

    for(int i = 0; i < x.length; i++){ 
    if(bs.get(x.length - (i + 1))){ 
     X[i] = x[i]; 
    } 
    else { 
     X[i] = 0; 
    } 
    } 

    return X; 
} 

結果將是:

x = [12, 2345, 232, 52, 24] 
b = 5 (i.e. 101 binary) 
X = [0, 0, 232, 0, 24] 

請注意,如果您想直接定義位,則可以將其設置在BitSet中。

1

只是一個for循環

int[] newarray = new int[length]; 
for(int i = 0; i < length; i++) 
{ 
    if(b[i]==1) 
     newarray[i] = x[i]; 
    else 
     newarray[i] = 0; 
} 

只要確保長度到處是一致的。

0

由於這樣的:

int i = 3; 
int[] yourArray; 
for (int i = 0; i < yourArray.length; i++) { 
    yourArray[i] = yourArray[i] & i == i ? yourArray[i] : 0; 
} 
+0

由於yourArray未初始化,因此此代碼將始終失敗。 –

0

試試這個:

String binSt = Integer.toBinaryString(5); // has no leading 0s 
    byte[] x = {12, 21, 21, 52, 24}; 
    byte[] xResult = new byte[x.length]; 
    int offset = x.length - binSt.length(); // to simulate leading 0s 
    for (int i = 0; i < xResult.length; i++) { 
     xResult[i] = (i-offset < binSt.length() && i-offset >= 0 && binSt.charAt(i-offset) == '1' ? x[i] : 0); 
    } 
    System.out.println(Arrays.toString(xResult));