2

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?

madth3
  • 7,275
  • 12
  • 50
  • 74
Stig Christian
  • 287
  • 1
  • 5
  • 14
  • The "Related" column on the right shows the following possible duplicates: http://stackoverflow.com/questions/1956160/good-tutorials-on-bitwise-operations-in-java, http://stackoverflow.com/questions/560956/bitwise-and-bitwise-inclusive-or-question-in-java – Péter Török Apr 24 '10 at 15:31

3 Answers3

2

Use a BitSet.

JRL
  • 76,767
  • 18
  • 98
  • 146
2

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
}
Brett Kail
  • 33,593
  • 2
  • 85
  • 90
0

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
  • 47,141
  • 22
  • 87
  • 101