tags:

views:

132

answers:

3

I have an array of bytes. I want to simulate corrupt data by changing one bit, two, and three bits.

How do I do this?

A: 

Use a BitSet.

JRL
+1  A: 

Use the xor (^) operator:

// Generate some data.
byte[] b = new byte[1024];
new Random().nextBytes(b);

// Simulate corruption of data by flipping the low 3 bits.
for (int i = 0; i < b.length; i++) {
  //b[i] ^= 0x1; // change one bit
  //b[i] ^= 0x3; // change two bits
  b[i] ^= 0x7; // change three bits
}
bkail
A: 

The usual way to set a bit in most languages is to 'or'(|) it with a bit mask with only that bit set, and the usual way to unset it is to 'and'(&) it with a bit mask without that bit set.

So make 8 set bit masks

byte setbm1 = 1; //00000001
byte setbm2 = 1 >>1;
byte setbm3 = 1>>2;
...
...
byte setbm8 = 1>>7; //10000000

and 8 'and' bit masks

byte unsetbm1 ^= setbm1; //11111110
..
..
byte unsetbm1 ^= setbm8; //01111111

To set the first bit use (assume array is a byte array and i is an integer)

array[i] |= setbm1

to unset it

array[i] ^= setbm1

Otherwise you can use http://java.sun.com/javase/6/docs/api/java/util/BitSet.html

Charles Ma