C語言 列印時資料型別要統一 ( u)

2021-09-05 12:47:39 字數 1752 閱讀 2101

出錯的程式:

#include #include #include typedef unsigned char byte;

typedef unsigned int dword;

typedef unsigned short word;

#define pri(fmt, ...) printf("["__file__"] <%s>_<%d> " ,__function__,__line__ );\

printf(fmt, ##__va_args__);

int main()

; b[0] = 0xef;

b[1] = 0xff;

b[2] = 0xff;

b[3] = 0xff;

dword a = (b[0] << 24) + (b[1] << 16) + (b[2] << 8) + (b[3]);

pri("a : %d \n", a);

return 0;

}

按照設想,a的值應該為:4026531839

但是執行之後:

root@ubuntu:/mnt/hgfs/ubuntu12.04-share/test# ./test

[test.c] _<28> a : -268435457

root@ubuntu:/mnt/hgfs/ubuntu12.04-share/test#

是乙個負值。

把列印語句更換為如下語句就沒問題了。

pri("a : %u \n", a);
執行結果:

root@ubuntu:/mnt/hgfs/ubuntu12.04-share/test# ./test

[test.c] _<28> a : 4026531839

root@ubuntu:/mnt/hgfs/ubuntu12.04-share/test#

注意變數型別。是int、char 、是有符號還是無符號。

如同下面的例子。

byte a = 199;

pri("a : %c \n", a);

/* pri("a : %u \n", a); */

return 0;

執行肯定是有問題的。

root@ubuntu:/mnt/hgfs/ubuntu12.04-share/test# ./test

[test.c] _<21> a : š

root@ubuntu:/mnt/hgfs/ubuntu12.04-share/test#

char範圍是 -128 ~ 127

unsigned char 範圍是 0 ~ 255;

如果按如下定義

byte a = 278;
編譯時有如下警告,是不能忽視的。

root@ubuntu:/mnt/hgfs/ubuntu12.04-share/test# gcc -o test test.c 

test.c: in function 『main』:

test.c:20:2: warning: large integer implicitly truncated to unsigned type [-woverflow]

root@ubuntu:/mnt/hgfs/ubuntu12.04-share/test#

C語言資料型別 一

todo 整型 短整型 16位 32767 32767 short si 32767 無符號短整型 16位 0 65535 unsigned short us 65535 printf short hd u short u n si,us 基本整型 32 64位 2147483622 2147483...

c語言(一)資料型別

一 分類 1.a 標量型別 a1 算術型別 a1基本型別 1 整型 標準整數型別 擴充的整數型別 2 實型 浮點型 實數浮點型別 複數浮點型別 3 字元型 a2列舉型別 a2 指標型別 b 聚合型別 b1 陣列型別 b2 結構型別 c 聯合型別 d 函式型別 2.描述物件的資料型別可分為 物件型別 ...

C語言 資料型別

基本型別 整形 int 字元型 char 實型 浮點型 單精度 float 雙精度 double 構造型別 陣列型別,結構型別 struct 聯合型別 uion 列舉型別 enum 指標型別 空型別 無值型別 void。常量 在程式執行過程中,其值不能被改變的量稱為常量。變數 變數代表記憶體中具有特...