简体   繁体   English

有没有一种简单的方法可以将带符号的char转换为没有符号扩展名的int?

[英]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. 在C语言中,我想将一个带signed char转换为一个int不带符号扩展名。 So if the signed char is 0xFF, the int would also be 0xFF. 因此,如果带signed char为0xFF,则int也将为0xFF。 Simply casting to an int won't work; 仅仅将其转换为一个int无效。 the result would be 0xFFFFFFFF (on a 32-bit machine). 结果将是0xFFFFFFFF(在32位计算机上)。

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. 您可以先转换为unsigned char 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 : 或者,正如Carl Norum所说,您可以简单地将其转换为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). 但请注意,因为有一个0xFF char值(十进制255)溢出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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