2006
06
23
18
09
signed vs unsigned.
話說在linux 2.6 kernel裡有下列程式碼.
include/linux/jiffies.h, line 109
109 #define time_after(a,b)
110 (typecheck(unsigned long, a) &&
111 typecheck(unsigned long, b) &&
112 ((long)(b) - (long)(a) < 0))
113 #define time_before(a,b) time_after(b,a)
include/net/tcp.h, line 742
742 static inline int before(__u32 seq1, __u32 seq2)
743 {
744 return (__s32)(seq1-seq2) < 0;
745 }
746
747 static inline int after(__u32 seq1, __u32 seq2)
748 {
749 return (__s32)(seq2-seq1) < 0;
750 }
事實上差別也只有先變成signed再做運算,和先作運算再變成signed。
似乎是沒有差別,根據程式跑出來的結果的確是沒問題的。
但是Q同事說,用char (0x7f 和 0x80)去運算時,會有問題。
而用下列程式去執行,跑出來的結果,的確會有問題。
#define time_after(a,b)
(((signed char)(b) - (signed char)(a)) < 0)
#include
int main()
{
unsigned char a=0x7f;
unsigned char b=0x80;
if (time_after(a,b)) {
printf("Error: a 0x7f>b 0x80n");
} else {
printf("OK: a 0x7f
}
return 0;
}
結果跑出:
Error: a 0x7f>b 0x80
問題出在相減時,Compiler會先轉成signed int再去相減。
但是這裡結果就不是我們所期望的。
.file "test.c"
.def ___main; .scl 2; .type 32; .endef
.text
LC0:
.ascii "Error: a 0x7f>b 0x8012