1

我正在用 C 语言做一些位移工作,并且正在阅读无符号字符。我与这些变量一起使用的每个函数是否都需要将无符号字符作为输入,或者因为我将值加载为无符号,它会自动保持第一位为正数?

基本上我需要做:

int Test1(unsigned char input1)
{
...
}

对于一切,或将:

int Test2(char input2)
{
...
}

够了吗?谢谢。

4

3 回答 3

2

int Test2(char input2) might not work. As largest unsigned char is greater than largest signed char(largest positive integer in the range).

But!

Since both unsigned char and signed char are of same size, whether you read it as signed char or unsigned char what is stored in the memory is the same. Only the interpretation is different when you access them.

Also char var does not mean that it is a signed char. It actually depends on compiler flags. Read here.

于 2012-11-19T15:18:45.250 回答
1

It will not change the value, but it could be interpreted differently, so it really depends on what you want to do inside the functions, for example:

unsigned char c = 255;

void Test1(unsigned char c)
{
    printf("%d\n", (c>100)); //prints 1
    printf("%d\n",  (unsigned char)c); //prints 255
}

void Test2(char c)
{
    printf("%d\n", (c>100)); //prints 0
    printf("%d\n",  (unsigned char)c); //prints 255
}
于 2012-11-19T15:22:44.443 回答
0

The largest possible unsigned char value is bigger than the largest possible signed char value (because you effectively need one bit's worth of information for the sign).

So, some legal unsigned char values in the first function won't be representable as a signed char when passed to the second. Does it really matter whether they get somehow truncated, or turn negative? They're obviously going to get damaged in some way.

Keep your types the same unless you're deliberately coercing them for some reason (eg, check your unsigned char is representable as a char). There may be exceptions where you have special knowledge about the contents, of course.

于 2012-11-19T15:18:15.653 回答