小编ran*_*guy的帖子

C:在无符号变量的情况下执行带符号变量的签名比较

我想要一个具有以下签名的函数:

bool signed_a_greater_than_signed_b(unsigned char a, unsigned char b);
Run Code Online (Sandbox Code Playgroud)

它的输出应该是1iff存储的位a的2的补码视图大于存储的位的2的补码视图b.否则输出应该是0.例如:

signed_a_greater_than_signed_b(0b10000000,any number) => 0
signed_a_greater_than_signed_b(0b01111111,any number other than 0b01111111) => 1
signed_a_greater_than_signed_b(0b00000000,0b00000001) => 0
signed_a_greater_than_signed_b(0b00000000,0b11111111) => 1
signed_a_greater_than_signed_b(0b00000000,0b00000000) => 0
Run Code Online (Sandbox Code Playgroud)

该函数不具有任何隐式/显式转换(因为这些转换是实现定义的,因此不可移植)

一个这样的实现是:

bool signed_a_greater_than_signed_b(unsigned char a, unsigned char b)
{
    // if 'signed' a is positive then 
    //     return 1 if a is greater than b or b is negative
    // otherwise, if 'signed' a is negative then 
    //     return 1 …
Run Code Online (Sandbox Code Playgroud)

c comparison unsigned signed casting

0
推荐指数
1
解决办法
856
查看次数

标签 统计

c ×1

casting ×1

comparison ×1

signed ×1

unsigned ×1