-
Two's Complement
Hey Guys,
I know this isn't a direct question about C, but it does relate.
When you want to get a two's complement of a number, you first get the one's compelement (or logicaly NOT it) and then add 1.
example:
0000 0011 = 3
1111 1100 = not
+1
---------------
1111 1101 = -3
So is the 2's complement just a unique number? Do I have to get over the fact that 1111 1101 isnt |3| in binary, but just unique?
1000 0000 = 128
0111 1111
+1
--------------
1000 0000 = -128
is -128 just an exception to the rule? i mean the sign bit has a double meaning?
-
Not exactly sure what you're asking. For subtraction, you add the 2's complement. You get funny results when your numbers get large.
-
Let's speak about bytes.
A byte is 8 bits long so from
00000000 eg 0
to 11111111.
It's a char in C.
Whether or not a char is signed or unsigned (by default) is dependant on the processor.
If chars are unsigned 11111111 is 255 and a byte goes from
0 to 255. There's no sign bit.
If chars are signed the rightest bit is the sign bit so 11111111 is
-156 and a byte goes from -156 to 155. The sign bit has a single meaning "-".
It's the same with words or longs.
Of course you can choose what you want with
signed char a;
unsigned char b;
-
As for as I know, when I say you get bad results with large numbers, you never want to use numbers that are large enough to fill the largest bit in the registers. Also, I've never seen this stated, but, between negative and positive numbers, you have a zero, and that is why you add the 1 to make a 2's comp.
-
a signed byte has a range of -128...127. not -156..155, gertfaller
2^Number of Bits - 1 = Largest Value
-
-
>> If chars are signed the rightest bit is the sign bit
Actually, it's generally the leftmost bit unless you're using an older compiler who doesn't compensate for the 'endian' difference between motorola and intel CPUs.
-
> the 'endian' difference between motorola and intel CPUs.
Motorola's big endian and Intel's little, right? (doing a little Micros review in my head)
-
For signed numbers, the most significant bit (msb) is the sign bit:
If msb = 0, number is positive
If msb = 1, number is negative
1000 0000 = -128
Positive 128 can't be stored in 8 bits (unless you aren't representing negative numbers).
-
Thank you, Govtcheez!
I just wondered what "little endian" means.
klausi