this is my code:
#include <stdio.h>
void main() {
char a, b;
char c;
printf("enter 2 chars: ");
a = getchar();
b = getchar();
c = a - b;
printf("%d",c );
}
I'm trying to find the absolute value between two chars, for example, 'A'&'a'=>32 'a'&'A'=>32 my code shows negative answer,what should I do without using abs function or if, I tried this:
printf("%u",c );
but it gives me 4294967264. is there any simple way to do it? it should use getchar and putchar!
Without branching: (assumes two's complement integer representation)
Split in pieces:
(c < 0)
gives0
whenc
is positive:c = (c^-0) + 0
~>c = c^0
... $foo XOR 0 gives $fooc = c
nothing to do.(c < 0)
gives1
whenc
is negative:c = (c^-1) + 1
...-1
in two's complement is all bits set (~0
)c = (c^(~0)) + 1
... a negativec
in two's complement XOR~0
gives-c - 1
c = -c - 1 + 1
~>c = -c
gcc 8.3 -O3: (cl v15.9.0-pre.3.0 produces equivalent assembly)