uint8_t / uint16_t / uint32_t /uint64_t 是什么數據類型
在nesc的代碼中,你會看到非常多你不認識的數據類型,比方uint8_t等。咋一看。好像是個新的數據類型,只是C語言(nesc是C的擴展)里面好像沒有這種數據類型啊!怎么又是u又是_t的?非常多人有這種疑問。論壇上就有人問:以*_t結尾的類型是不是都是long型的?在baidu上查一下,才找到答案,這時才發覺原來自己對C掌握的太少。
那么_t的意思究竟表示什么?詳細的官方答案沒有找到,只是我認為有個答案比較接近。它就是一個結構的標注。能夠理解為type/typedef的縮寫,表示它是通過typedef定義的,而不是其他數據類型。
uint8_t,uint16_t。uint32_t等都不是什么新的數據類型。它們僅僅是使用typedef給類型起的別名。新瓶裝老酒的把戲。
只是,不要小看了typedef,它對於你代碼的維護會有非常好的作用。
比方C中沒有bool,於是在一個軟件中。一些程序猿使用int,一些程序猿使用short,會比較混亂。最好就是用一個typedef來定義,如:
typedef char bool;
一般來說,一個C的project中一定要做一些這方面的工作,由於你會涉及到跨平台。不同的平台會有不同的字長。所以利用預編譯和typedef能夠讓你最有效的維護你的代碼。為了用戶的方便。C99標准的C語言硬件為我們定義了這些類型,我們放心使用就能夠了。
依照posix標准,一般整形相應的*_t類型為:
1字節 uint8_t
2字節 uint16_t
4字節 uint32_t
8字節 uint64_t
附:C99標准中inttypes.h的內容
00001 /*
00002 inttypes.h
00003
00004 Contributors:
00005 Createdby Marek Michalkiewicz <marekm@linux.org.pl>
00006
00007 THISSOFTWARE IS NOT COPYRIGHTED
00008
00009 Thissource code is offered for use in the public domain. You may
00010 use,modify or distribute it freely.
00011
00012 Thiscode is distributed in the hope that it will be useful, but
00013 WITHOUTANY WARRANTY. ALLWARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
00014 DISCLAIMED. This includes but is not limited towarranties of
00015 MERCHANTABILITYor FITNESS FOR A PARTICULAR PURPOSE.
00016 */
00017
00018 #ifndef __INTTYPES_H_
00019 #define __INTTYPES_H_
00020
00021 /* Use [u]intN_t if you need exactly N bits.
00022 XXX- doesn't handle the -mint8 option. */
00023
00024 typedefsigned char int8_t;
00025 typedefunsigned char uint8_t;
00026
00027 typedefint int16_t;
00028 typedefunsigned int uint16_t;
00029
00030 typedeflong int32_t;
00031 typedefunsigned long uint32_t;
00032
00033 typedeflong long int64_t;
00034 typedefunsigned long long uint64_t;
00035
00036 typedefint16_t intptr_t;
00037 typedefuint16_t uintptr_t;
00038
00039 #endif