Search code examples
objective-cintunsigned-char

Objective C unsigned char to negative int


I've to transform

unsigned char x = 0xEC in int y = -20

unsigned char x = 0xF0 in int y = -16

if I cast like this (assuming x = 0xF0)

int y = (int)x

I obtain x = 240 that is the correct decimal representation of 0xF0. Where I'am wrong ? How can I get a negative number ?


Solution

  • Converting the unsigned char to a signed char first, then going to an int will give you the result you want:

    unsigned char x = 0xEC;
    char x1 = (char)x;
    int x2 = x1;
    

    As CRD points out, the C specification leaves the fact that char could either be signed or unsigned, so the safest solution here is to be explicit.

    signed char x1 = (signed char)x;