Signed != Unsigned
Problems of Sign Extension:
void main()
{
int a=-2;
unsigned int b=1;
long c = a + b;
long c1 = a + (long) b;
long long d=c; // to get a consistent size for printing (on both architectures, 32 and 64 bit).
…
}
PROBLEM: When executed on a 32-bit architecture, the result is -1 (0xffffffff). When run on a 64-bit architecture, the result is 4294967295 (0×00000000ffffffff), which is probably not what you were expecting
Rule #1 : Now, when you add a (int) + b (uint) : The result is : Unsigned. Thus, a + b results in a unsigned integer (-1) which is 0xffffffff.
Rule #2: When unsigned int numbers are promoted to long’s. They are not sign Extended. Thus, -1 which is 0xffffffff is simply promoted to 0×00000000ffffffff which is a very high number. Note: This problem does not come on a 32 bit OS. Since long is 4 bytes.
What? The Idea is simple: unsigned quantity does not have a sign attached to it, right? so if unsigned quantity is promoted to a long(or unsigned long) then they simply cannot be sign extended!
However, signed quantities do have a sign, thus when they are promoted to a long, it is all duly taken care. i.e:
Rule #3: Signed values are always sign extended when promoted to a larger
type, even if the resulting type is unsigned.
(unsigned or signed) Long = Signed int will Work.
i.e. Signed values are always sign extended when promoted to a larger type, even if the resulting type is unsigned.
int a = -1;
long v = a;
unsigned long v1 = a;
printf(“%d %ld %ld\n”,a, v, v1);
Output (on a 64 bit value) is: -1 -1 18446744073709551615
The above big value clearly shows that when signed integer -1 was promoted to a signed long value (which would be 64th bit (sign bit) was set as 1).
Rule #5: Constants (unless modified by a suffix, such as 0×8L) are the
smallest size that will hold the value. For numbers written in
hexadecimal, this includes both signed and unsigned int, long,
and long long types. For decimal numbers, this only includes
signed types.
About this entry
You’re currently reading “Signed != Unsigned,” an entry on WoOd’s TechLog
- Published:
- November 28, 2008 / 3:52 pm
- Tags:
- 64 bit OS, Sign Extension, Sign promotion
No comments yet
Jump to comment form | comments rss [?] | trackback uri [?]