c - 如何将 Signed Char 与文字常量进行比较?

标签 c type-conversion

API 提供了一个函数signed char getDirection();,它返回 1 代表“前进”,0 代表“静止”,-1 代表“后退”。

当然,如 these 中所述questions , 一个简单的比较:

    if(getDirection() == -1) { ... }

失败。好的,我明白为什么它失败了。但我就是找不到如何让它工作!我尝试将左侧转换为 (int),将右侧转换为 (signed char),仍然是 nada...

编辑:

 signed char a = getDirection();
 printf("%d\n",(int) a);
 printf("%d\n",(int) getDirection());

结果:

 -1
 255

edit2:每个请求:

const signed char getDirection(uchar d)
{
    if(d >= config.directional_inputs.channelCount) return -2;

    return shm->input_state.directional_inputs[d].direction;
}

最佳答案

如果您确定 getDirection() 确实返回一个带符号的字符,它应该可以工作,因为 0xff 的带符号字符应该正确地提升为 -1 整数.

如果不确定,可以尝试写

int dir = getDirection();
// optionnally for extensive tests : fprintf(stderr, "getDirection : %d\n", dir);
if ((dir == -1) || (dir == 255)) { ... }

255 会捕获任何转换问题,例如 getDirection() 返回一个带符号的字符...您上次编辑的建议...

关于c - 如何将 Signed Char 与文字常量进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31520410/

相关文章:

c - 打印 Bison 中的所有减少

c++ - 将字节 [4] 存储在一个 int 中

c - 将浮点指针设置为从头文件读取的字符数组

关于 fgets() 函数字符限制的 C 编程?

c++ - IP 头位顺序不清楚

c - 二进制表达式 ('double' 和 'double' 的无效操作数)

mysql - 为什么可以在 MySQL 中使用数字字符串值来设置整数字段,并且这是一个始终有效的功能吗?

c++ - 使用 HashTable 实现实现 HashMap

r - 我们如何将整数拆分为 R 中其组成数字的向量

c# - VB.NET 中的 "(byte)"是什么?