2013-04-04 60 views
0

的所有補我有一個字節數組myByteArray[82]如何在字節數組改變37位到現有的值

我想這個數組補值改變正好37位。即。如果bit0具有'1',我想將其更改爲'0'。我需要改變前面37個這樣的位來在這個字節數組中引入錯誤。

請建議如何操作

+0

其中有37位?最左邊的?最右邊的?最左邊(或最右邊)37個1位,無論它們在哪裏出現?請告訴我們你的意思是什麼(它不一定是82字節長),更重要的是,_顯示你已經嘗試過的東西。 – 2013-04-04 04:49:45

+0

感謝您的回覆......實際上我只是想改變任何37位(反轉它們)..在長度爲82的 – Rookie 2013-04-04 04:57:38

回答

2

這並不完全清楚你正在做什麼。我最好的理解是你有一個82字節的數組,並且你想反轉數組的最低37位。因爲一個字節爲8位,所以你可以這樣做:

byte[] myByteArray = new byte[82]; 
// invert lowest 32 bits, 8 at a time 
for (int i = 0; i < 4; ++i) { 
    myByteArray[i] = (byte)(~myByteArray[i]); 
} 
// invert next five bits 
myByteArray[4] = (byte) (
    (myByteArray[4] & 0xE0) // top 3 bits unchanged 
    | 
    ((~myByteArray[4)) & 0x1F) // bottom 5 bits inverted 
    ); 
+0

的字節數組中引入隨機數組非常感謝!我將學習這段代碼並學習如何做到這一點!真的有幫助! – Rookie 2013-04-04 04:58:29

1

這工作:

int nBits = 37; 

int i = 0; 

for (; i<nBits/8; ++i) 
    myByteArray[i] = (byte)((byte) myByteArray[i]^0xFF); 

myByteArray[i] = (byte)(myByteArray[i]^((0xFF >>> 5)^0xFF)); 

無論你做的0xFF的最終XOR最後一行取決於你是否考慮最重要的位是第一位(然後使用它)或最後一位(然後省略它);

+0

非常感謝你!這給了我一個思考的方向......這非常有幫助! – Rookie 2013-04-04 04:58:01

+0

我編輯了代碼,以便它能正常工作。 Waaaa,我忘記了Java比C更不友好。 – 2013-04-04 05:16:22

0

要翻轉特定37位,隨機選擇的:

// array of 82 bytes with 37 selected bits set to 1, all the rest zero 
// you could generate this programmatically as well if you need a different 
// set of bits each time, but your question implies you don't 
byte[] mask = { 0x00, 0x01, 0x02, 0x80, .... 0x00 }; 

for (int i=0; i<myByteArray.length; i++) 
{ 
    myByteArray[i] ^= mask[i]; 
} 

使用位異或操作者^。 xor的真值表是

M a s k 
    | 0 | 1 
D -+---+--- 
a 0| 0 | 1 
t -+---+--- 
a 1| 1 | 0 

無論在掩碼中有1位,數據中的相應位都將被翻轉。

2

嘗試

byte[] a82 = ... 
    Set<Integer> set = new HashSet<Integer>(); 
    while (set.size() < 37) { 
     set.add((int) (Math.random() * 82)); 
    } 
    for (int i : set) { 
     int ibyte = i/8; 
     int ibit = i % 8; 
     int m = 1 << ibit; 
     a[ibyte] ^= m; 
    } 
+0

這將在82字節中隨機更改爲37位。它肯定會引入錯誤。我喜歡! – 2013-04-04 05:22:14

+0

不錯的做法。 +1但是,OP有82 * 8 = 656位可用;您的代碼只會隨機選擇前82箇中的37個。另外,不是使用'(int)(Math.random()* 656)',而是使用'rand.nextInt(656)'創建一個java.util.Random對象。最後,不是'i/8',而是使用'i >> 3'而不是'i%8',使用'i&7'。 (編譯器可能會自動進行最後兩次優化,但它自己不能傷害。) – 2013-04-04 19:21:12