DEV Community

codemee
codemee

Posted on

1

從 3 - 5 談 C 語言無號整數的運算

如果說 3 - 5 有可能是正數, 你信嗎?在 C 語言裡, 如果是無號 (unsigned) 整數, 那 3 - 5 就會是正數, 這是因為無號整數會遵循除以 $2^n$ 取餘數的規則, 因此 3 - 5 實際運算結果雖然是 -2, 但若是無號整數, 因為不會有負數, 會依循上述規則取結果, 以下是簡單的範例

#include<stdio.h>

unsigned char a = 5, b = 3, c;

int main()
{
    c = b - a;
    printf("%d\n", c);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

執行結果如下:

254


** Process exited - Return Code: 0 **
Enter fullscreen mode Exit fullscreen mode

這是因為 unsigned char 是 8 位元, 因此依照規則就會是 -2 % 256 得到 254。

相同的道理, 如果無號整數溢位 (overflow) 了, 也是一樣, 例如以下的範例

#include<stdio.h>

unsigned char a = 5;

int main()
{
    a += 256;
    printf("%d\n", a);
    return 0;
}

Enter fullscreen mode Exit fullscreen mode

執行結果如下:

5


** Process exited - Return Code: 0 **
Enter fullscreen mode Exit fullscreen mode

因為 (5 + 256) % 256 仍然是 5 的關係。

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay