5

I have an 80 element char array and I am trying to specific elements to an integer and am getting some number errors. Array element 40 in hex is 0xC0. When I try assigning it to an integer I get in hex 0xFFFFC0, and I dont know why.

char tempArray[80]; //Read in from file, with element 40 as 0xC0
int tempInt = (int)tempArray[40]; //Output as 0xFFFFC0 instead of 0x0000C0
2
  • 10
    Because 0XC0 is negative in char, and the cast is preserving the sign as an int. Commented Jul 21, 2014 at 15:11
  • 1
    int tempInt = (int)tempArray[40]; --> unsigned tempInt = (unsigned)tempArray[40]; will do the trick. Commented Jul 21, 2014 at 15:12

5 Answers 5

14

Depending on your implementation, a char type in C++ is either a signed type or an unsigned type. (The C++ standard mandates that an implementation chooses either scheme).

To be on the safe side, use unsigned char in your case.

Sign up to request clarification or add additional context in comments.

1 Comment

Up-vote for you, I forgot about the fact that it could be platform dependent.
3

This is so because char is treated as signed number, and the promotion to int preserves the sign. Change the array from char to unsigned char to avoid it.

Comments

3

Because 0XC0 is negative in char, and the cast is preserving the sign as an int. You should use unsigned char if you want to maintain the directly binary translation or as a purely positive value

Comments

1

for more convenience, I always use unsigned and signed always before declaration and casting. you can write the following:

unsigned char tempArray[80]; //Read in from file, with element 40 as 0xC0
unsigned int tempInt = (unsigned int)tempArray[40]; //Output as 0xFFFFC0 instead of 0x0000C0

2 Comments

Your cast is unnecessary and the output is 0xC0 not 0xFFFFC0
It well might be. but this kind of casting makes the code more readable.
0

char may be signed, so converting from a negative char value will result in a negative int value, which is usualyl represented in two's complement, resulting in a very high binary representation.

Instead, either use int tempInt = 0xFF & tempArray[40], define tempArray as unsigned char, or cast to unsigned char : int tempInt = (unsigned char)tempArray[40] (unsure if this is defined behaviour).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.