Angus
Angus

Reputation: 12621

signed_extension in c

I have tried the below program and getting the output as 72. I could not understand how it outputs as 72.

#include <stdio.h>
int main()
{
    int a=0x27ea4d72;
    char x=a;
    printf("%x",x);
    return 0;
}

Upvotes: 3

Views: 119

Answers (2)

Omri Barel
Omri Barel

Reputation: 9480

From the C standard:

6.3.1.3 Signed and unsigned integers

  1. When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
  2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
  3. Otherwise, the new type is signed and the value cannot be represented in it; the result is implementation-defined.

The conversion falls into case #3 because the values are signed. So the result is implementation-defined.

However, for the code:

#include <stdio.h>

int main()
{
    unsigned long a = 0x27ea4d72UL;
    unsigned char x = a;
    printf("%x",x);
    return 0;
}

The conversion falls into case #2 in which case the standard basically says that the result would be 0x27ea4d72 % (UCHAR_MAX+1). Where UCHAR_MAX is 255 (most common case), you'd get 0x72.

Upvotes: 4

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136286

Since int is normally wider than char, char x=a; truncates the value of int being assigned.

From "The New C Standard" book:

In the case of conversions to narrower integer types, the generated machine code may depend on what operation performed on the result of the cast. In the case of assignment the appropriate least-significant bits of the unconverted operand are usually stored. For other operators implementations often zero out the nonsignificant bits (performing a bitwise-AND operation is often faster than a remainder operation) and for signed types sign extend the result

Upvotes: 3

Related Questions