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)gives0whencis positive:c = (c^-0) + 0~>c = c^0... $foo XOR 0 gives $fooc = cnothing to do.(c < 0)gives1whencis negative:c = (c^-1) + 1...-1in two's complement is all bits set (~0)c = (c^(~0)) + 1... a negativecin two's complement XOR~0gives-c - 1c = -c - 1 + 1~>c = -cgcc 8.3 -O3: (cl v15.9.0-pre.3.0 produces equivalent assembly)