認識 `<stdint.h>` (一)

<stdint.h>是C99的標準,在裏面定義了8,16,32,64位的有符號和無符號整數類型定義。 分別是:

  • int8_t, int16_t, int32_t, int64_t;
  • uint8_t, uint16_t, uint32_t, uint64_t;

那麼,這些類型具體是什麼呢?讓我們一起追下源代碼。我們看下 glibc2.38 的源代碼。glibc 最新版本是2.38,正在開發中的是2.39,2.40,每6個月一個版本,這個項目從1988開始已經35年了,所有的版本一共144個版本。

https://sourceware.org/glibc/wiki/Glibc Timeline

可以在線查看glibc的源代碼:https://sourceware.org/git/?p=glibc.git;a=summary

不過我們可以看另外一個更適合查看的地址:https://elixir.bootlin.com/glibc/latest/source

通過層層追蹤,可以看到 stdint.h裏 對這幾個整型的定義

0)查看 stdlib/stdint.h
在線查看: https://elixir.bootlin.com/glibc/latest/source/stdlib/stdint.h

可以看到裏面依賴

<bits/stdint-intn.h>
<bits/stdint-uintn.h>

a)進一步查看:bits/stdint-intn.h
在線查看: https://elixir.bootlin.com/glibc/latest/source/bits/stdint-intn.h

可以看到

typedef __int8_t int8_t;
typedef __int16_t int16_t;
typedef __int32_t int32_t;
typedef __int64_t int64_t;

進一步查看:bits/types.h
在線查看:https://elixir.bootlin.com/glibc/latest/source/posix/bits/types.h#L37

這是平臺相關的定義,例如posix

typedef signed char __int8_t;
typedef unsigned char __uint8_t;
typedef signed short int __int16_t;
typedef unsigned short int __uint16_t;
typedef signed int __int32_t;
typedef unsigned int __uint32_t;
#if __WORDSIZE == 64
typedef signed long int __int64_t;
typedef unsigned long int __uint64_t;
#else
__extension__ typedef signed long long int __int64_t;
__extension__ typedef unsigned long long int __uint64_t;
#endif

b)進一步查看 bits/stdint-uintn.h
在線查看: https://elixir.bootlin.com/glibc/latest/source/bits/stdint-uintn.h

可以看到

typedef __uint8_t uint8_t;
typedef __uint16_t uint16_t;
typedef __uint32_t uint32_t;
typedef __uint64_t uint64_t;

進一步查看:bits/types.h
在線查看:https://elixir.bootlin.com/glibc/latest/source/posix/bits/types.h#L37
同a)

這樣我們就大概知道在 posix 平臺上的glibc裏:

  • int8_t 實際上就是 signed char
    • signed char 一般簡寫爲 char
  • uint8_t 實際上就是 unsigned char
  • int16_t 實際上就是 signed short int
    • short int 一般簡寫爲 short
    • signed short int 一般簡寫爲 short
  • uint16_t 實際上就是 unsigned short int
    • unsigned short int 一般簡寫爲 unsigned short
  • int32_t 實際上就是 signed int
  • uint32_t 實際上就是 unsigned int

而對於 int64_tuint64_t 則需要判斷當前系統是32位的還是64位的

  • 如果是64位,則實際上
    • __int64_t 就是 signed long int,一般 long int 簡寫爲 long,從而 signed long int 簡寫爲 long
    • __uint64_t 就是 unsigned long int 一般簡寫爲 unsigned long
  • 如果在32位上,那麼
    • __int64_t 就是 signed long long int 也就是 signed long long
    • __uint64_t 就是 unsigned long long int 也就是 unsigned long long

這樣通常情況下,認爲下面兩組整數類型的定義是等價的是可以的:

使用基本整數類型定義,他們分別是 8 bytes, 16 bytes, 32 bytes, 64 bytes 的有符號整數和無符號整數:
char, short, int , long long,
unsigned char,unsigned short,unsigned int, unsigned long long

使用C99標準,使用<stdint.h>裏的定義,則可以使用這組:
int8_t, int16_t, int32_t, int64_t,
uint8_t, uint16_t, uint32_t, uint64_t

--end--

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章