-2 is stored as its 2's complement which is 0b1111_1110 the decimal representation of this chunk of data is 254, right-?
Yes, this is true for typical modern system.
Now, my question is how will ARM processors differentiate between a "-2" and a "254" since both their binary representation is same ?
Processor doesn't; the compiler does.
Let's say you have expression value > 0
. Variable value
and constant 0
both have a types. Depending on these types, compiler chooses what CPU instructions to use. So signed and unsigned comparison could result in different compiler output.
Processor doesn't know about the types in your code. It simply executes these selected instructions.
Example with ARM64 gcc:
int icmp(int num) {
return num > 0;
}
int ucmp(unsigned int num) {
return num > 0;
}
icmp:
sub sp, sp, #16
str w0, [sp, 12]
ldr w0, [sp, 12]
cmp w0, 0
cset w0, gt
and w0, w0, 255
add sp, sp, 16
ret
ucmp:
sub sp, sp, #16
str w0, [sp, 12]
ldr w0, [sp, 12]
cmp w0, 0
cset w0, ne
and w0, w0, 255
add sp, sp, 16
ret
See how the compiler generated slightly different cset
instruction.