user2840470
user2840470

Reputation: 979

Converting element in char array to int

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

Upvotes: 5

Views: 1047

Answers (5)

axnsan
axnsan

Reputation: 917

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).

Upvotes: 0

milaniez
milaniez

Reputation: 1111

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

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234875

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.

Upvotes: 14

aruisdante
aruisdante

Reputation: 9115

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

Upvotes: 3

Wojtek Surowka
Wojtek Surowka

Reputation: 21013

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.

Upvotes: 3

Related Questions