Introducing errors by flipping bits
I have a character array in C i开发者_如何学运维nto which I want to introduce errors by flipping some bits.
How can I flip bits and introduce errors?
You can flip bits using the xor operator:
x = x ^ mask;
x ^= mask; // Same functionality as above.
For example, if mask
is 1
, the least significant bit is flipped. You can create any desired mask by bit-shifting the 1: mask = 1 << k;
where k
is the number of bits to shift.
For distributing the errors, use a random number generator. rand()
/ srand()
should suffice if this is for test purposes.
To flip a bit you can use the bit shifting and bitwise xor operators.
unsigned char flip(unsigned char c, int bit) {
return c ^ (1 << bit);
}
You can also flip more than one bit by using a bitmask other than (1 << bit)
, which has just one bit set:
unsigned char flip(unsigned char c, unsigned char mask) {
return c ^ (1 << mask);
}
// flip bits 0 and 3 (00001001 = 0x09)
flip(c, 0x09);
精彩评论