SandBag_1996
SandBag_1996

Reputation: 1601

Hexadecimal to decimal with char giving strange results?

I ran into a very strange problem. I think I am missing some very basic thing here. When I do this:

    char buffer[1] = {0xA0};
    int value=0;
    value = (int)buffer[0];
    printf("Array : %d\n",value); 

I get result as -96, which shouldnt happen. It should give me 160, as hexa number 0xA0 means 160 in decimal. When I put small values in buffer like 0x1F, it works fine. Can anyone tell me what am I missing here?

Upvotes: 0

Views: 231

Answers (1)

Mitch Wheat
Mitch Wheat

Reputation: 300797

char is signed -128 to 127

Declare buffer as unsigned char or cast to unsigned char:

char buffer[1] = {0xA0};
int value=0;
value = (unsigned char)buffer[0];
printf("Array : %d\n",value); 

Upvotes: 6

Related Questions