Dennis
Dennis

Reputation: 41

Char to int typecast fails

I have the following small snippet where i cast an integer to a char. Afterwards, i cast it back to an int.

The expected result: the integer is 138 What happens: the integer is -118

char arr[10];
int a = 138;
arr[0] = a;
printf("%d", arr[0]);

printf shows -118. The fix that i found is changing the array to an integer array, but I'd like to know why the typecast fails.

This only happens with some integer values. All values upto 127 seem to work just fine.

Upvotes: 0

Views: 63

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 224102

In your C implementation, char uses eight bits, is signed, and uses two’s complement to represent negative numbers. It can represent values from −128 to 127.

When you assign 138 to a char, it cannot be represented. Instead, it is converted to char in an implementation-defined way.

The binary numeral for 138 is 10001010. Your implementation converts it to char by using the same bit pattern, so the result is the bits 10001010 are stored in the char. In eight-bit two’s complement, these bits represent −118, so that is the value you get when you use the char after the assignment.

Upvotes: 2

Related Questions