0

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.

Dennis
  • 41
  • 4
  • 1
    Do you mean 128, not 118? – Eric Postpischil May 05 '20 at 02:47
  • I checked my code, the actual int is 138. I've edited the Question. – Dennis May 05 '20 at 02:55
  • 1
    The answer by @EricPostpischil is correct aside from the fact that 128 was mentioned instead of 138. If you have an N-bit signed `value` and `value >= 2^(N-1)`, you can use `-(2^N) + value` to see how `value` is interpreted. In this case, `N=8`, resulting in `2^(8-1) = 2^7 = 128`, and `138 >= 128`, so you'd calculate the resulting value as `-(2^8) + 138 = -118`. This is moreso an explanation of where -118 came from rather than an answer, and even this isn't the whole story (10000000=-128 may be a "trap representation" on some implementations, though I've never encountered that myself). – MemReflect May 05 '20 at 03:42
  • The maximum value `char` can have is `CHAR_MAX` (remember to `#include `) --- `printf("max char: %d\n", CHAR_MAX);` – pmg May 05 '20 at 11:50

1 Answers1

2

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.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312