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?

1

3 Answers 3

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
}
Sign up to request clarification or add additional context in comments.

Comments

2

Use a BitSet.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.