I have this little program which reads a long text document from allomany.txt.It contains a long text where we have some numbers.Now I need to falsify every number: Let is assume the program needs to read the text from file and I need to find a number(the number is string).Then I need to check if the string is a number. If yes then I need to falsify it by using bitwise operations.
Falsification: if I find a number in string(atoi
, sscanf
) then I need to increment the number which is found in the string. Example: if the program finds 14 we increase it 15 using bitwise operations. I found an example for this on the net if I remember correctly: (-(~n))
. If I don't use bitwise operations it works.
The question: how to do this with bitwise operations ?
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fin,*fout;
char *token, s[1000];
fin = fopen("allomany.txt","rt");
fout = fopen("hamisitott.txt","wt");
while (fscanf(fin, "%[^\n]\n", s) != EOF) {
token = strtok(s, " ");
while (token != NULL) {
if (atof(token) > 0)
fprintf(fout, "%g ", atof(token) + 1);
else fprintf(fout, "%s ", token);
token = strtok(NULL, " ");
}
fprintf(fout, "\n");
}
fclose(fin);
fclose(fout);
return EXIT_SUCCESS;
}
Incrementing the numbers with bitwise operations seems a bit complicated, I suggest a simple alternative: change every digit in the file from even to odd and vice versa by flipping the low order bit:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fin = fopen("allomany.txt", "r");
FILE *fout = fopen("hamisitott.txt", "w");
int c;
if (fin == NULL || fout == NULL) {
fprintf(stderr, "cannot open files\n");
exit(EXIT_FAILURE);
}
while ((c = getc(fin)) != EOF) {
if (c >= '0' && c <= '9')
c = '0' + ((c - '0') ^ 1);
putc(c, fout);
}
fclose(fin);
fclose(fout);
return EXIT_SUCCESS;
}
You could also implement other permutations of digits with a different expression (but without bitwise operations):
c = "9876543210"[c - '0'];
EDIT I changed c ^= 1
into c = '0' + ((c - '0') ^ 1)
to avoid assuming that '0'
be even. The C Standard only guarantees that digits '0'
through '9'
are adjacent and strictly positive.