-1

I've written code which looks like this:

char* xor_and_print(byte arr[], size_t buffSize, byte key)
{
    size_t i;

    for(i = 0; i < buffSize; i++)
    {
        printf("%c", (arr[i] & ~key) | (key & ~arr[i]));
    }
    putchar('\n');
}

This is an xor operation blown up into more instructions. I am using gcc-6.3.0. Even when I compile with -O0 flag, gcc turns this into one single xor instruction in the disassembly. Is it possible to coerce it into writing those specific asm instructions with a flag or must I use inline assembly language?

the_endian
  • 2,259
  • 1
  • 24
  • 49
  • 2
    There is no general way to have any piece of non-asm C output a specific sequence of assembly instructions, no. – that other guy Mar 18 '19 at 22:41
  • 2
    Declaring either `arr` or `key` as `volatile` makes it emit a lot more instructions. It depends on what exactly you want. E.g. it seems silly to force a `not key` every iteration. – o11c Mar 18 '19 at 22:51

1 Answers1

2

Using volatile should avoid this optimization:

for(i = 0; i < buffSize; i++)
{
    byte volatile b = arr[i];
    printf("%c", (b & ~key) | (key & ~b));
}

But it will stay unoptimized for higher optimization levels too.

ensc
  • 6,704
  • 14
  • 22