0

For days I have been stuck on this problem: I have an input.bin file and in another output.bin file I want to write every single character of the first file but with the addition of the bit 1111 before and after each of them so that when I give bash od -t x1, will be shown each character with the letter f before and after.

Content of input.bin if I read it doing od -t x1 input.bin from bash:

0000000 30 47 3b 23 25 3f 4d 5d 42 52 3d 60 51 26 45 7d
0000020 50 2e 3e 51 5c 2c 2d 20 52 55 47 7d 22 58 47 46
...

The output I want is like:

0000000 f3 0f f4 7f f3 bf f2 3f f2 5f f3 ff f4 df f5 df f4 2f f5 2f f3 df f6 0f f5 1f f2 6f f4 5f f7 df
0000020 f5 0f f2 ef f3 ef f5 1f f5 cf f2 cf f2 df f2 0f f5 2f f5 5f f4 7f f7 df f2 2f f5 8f f4 7f f4 6f
...

This is my last attempt, but I get 31 31 31 31 00 instead of 1111:

    FILE *in, *f4;
    in = fopen("input.bin", "rb");
    char ch;
    char ao[] = "1111";
    f4 = fopen("output.bin", "wb+");
    while (ch != EOF) {
        if ((ch = fgetc(in)) != EOF) {
            printf("%c ", ch);
            fwrite(ao, 1, sizeof(ao), f4);
            fprintf(f4, "%c", ch);
            fwrite(ao, 1, sizeof(ao), f4);

        }
    }
    fclose(in);
    fclose(f4);

Can you help me?

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 4
    So looks like you want to replace each byte `0xXY` with *two bytes* `0xFX 0xYF`. Now, can you do it with a single byte? (Hint: You need bitwise operations. Can get away with arithmetics too though.). Your code has pretty much nothing to do with what you are asking to achieve. – Eugene Sh. May 30 '22 at 20:12
  • 5
    For a start `char ch;` should be `int ch;` Then don't use `fprintf` but `fwrite` or `fputc` of two bytes `0xF0 | (ch >> 4)` and `0x0F | ((ch & 0xF) << 4)` Note there are about zero C library functions that work with `char` type (except arrays). It's a "beginner's assumption" that a 'character' should be a `char`. – Weather Vane May 30 '22 at 20:17
  • [Why does fgetc() return int instead of char?](https://stackoverflow.com/q/49063518/995714) – phuclv May 31 '22 at 03:04

1 Answers1

2

Using the character i/o primitives seems simpler. I'm not 100% sure it's "C standard" portable, but this ought to work just about everywhere.

void convert(FILE *in, FILE *out) {
  int ch;
  while ((ch = getc(in)) != EOF) {
    putc(0xf0 | (ch >> 4), out);
    putc((ch << 4) | 0x0f, out);
  }
}

Gene
  • 46,253
  • 4
  • 58
  • 96