简体   繁体   中英

Is there a simple way to convert a signed char to an int without sign extension?

In C, I would like to convert a signed char to an int , without sign extension. So if the signed char is 0xFF, the int would also be 0xFF. Simply casting to an int won't work; the result would be 0xFFFFFFFF (on a 32-bit machine).

This seems to work (and is already pretty simple):

int convert(signed char sc) {
    return 0xFF & (int) sc; 
}

But is there a simpler or more idiomatic way?

Edit: Fixed function

You can cast to unsigned char first. Assuming a definition:

signed char c;

You could just do:

int i = (unsigned char)c;

You can also use an union (the behavior is implementation-defined, but it's largely supported by the compilers).

int
convert(signed char ch)
{
    union {
        signed char c1;
        int c2;
    } input = { ch };
    return input.c2;
}

Or, as Carl Norum said, you can simply cast to unsigned char :

int 
convert(signed char ch)
{
    return (int)(unsigned char)ch;
}

But take care, because there is an overflow with 0xFF char value (255 in decimal).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM