Skip to content

Instantly share code, notes, and snippets.

@bradhe
Created May 8, 2012 08:03
Show Gist options
  • Save bradhe/2633434 to your computer and use it in GitHub Desktop.
Save bradhe/2633434 to your computer and use it in GitHub Desktop.
Given a string (provided as parameter), randomly flip ONE BIT in it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
void flip(char * str, int len) {
int byte, bit, bias;
char mask;
/* mmm, seeeds */
srand(time(NULL));
/* We want some bias towards the middle of the string. */
bias = (len / 3);
byte = rand() % (len - (bias * 2));
/* Construct a nice mask for this... */
bit = rand() % (sizeof(char) * 8);
mask = 2 << bit;
str[byte] = str[byte] ^ mask;
}
int main(int argc, char ** argv) {
int i, cnt, offset, len;
char * str;
cnt = 0;
for(i = 1; i < argc; i++) {
cnt += strlen(argv[i]);
cnt++; // Space or end of line character.
}
/* Null-terminated, of course. */
str = (char *)malloc(sizeof(char) * cnt);
memset(str, '\0', sizeof(char) * cnt);
offset = 0;
for(i = 1; i < argc; i++) {
len = strlen(argv[i]);
memcpy(str+offset, argv[i], len);
if(i < argc-1) {
str[offset+len] = ' ';
}
offset += len+1;
}
/* Randomly flip one of the bits in one of the characters. */
flip(str, cnt);
printf("%s\n", str);
free(str);
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment