15
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C99のint32_t型などをprintfに渡す方法

Last updated at Posted at 2017-04-23

C99からサイズ固定の整数型が定義できるようになったわけですが、そのあたりの整理。

前提

Cは伝統的にintlongが何バイトかの保証がありません1。これらの整数型に対してはCPUアーキテクチャごとに最適なサイズが割り振られるので、Cプログラマはintが何バイトだろうと動くコードを書かねばなりません2

とはいえサイズを明示したいこともあるよね、ということでC99からサイズ固定の型が登場しました。

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

符号あり・符号なしの8,16,32,64bitの整数型が明示的に使えます。やりましたね!

これらの型は<inttypes.h>で定義されています。

printfで使いたい

これらサイズ固定の整数型をprintfで使いたいときのために、適切な指示子に展開するマクロが存在します。

# include <stdio.h>
# include <inttypes.h>

int main(void) {
    int32_t i = 32;
    printf("%"PRIx32"\n", i); // 20
    return 0;
}

普段なら%xと書くはずのところで、マクロPRIx32を利用しています。このうちxの部分は普段の指示子と同様d(符号あり10進)、Xおよびx(16進)、o(8進)、u(符号なし10進)が利用できます。最後の数字は整数型のサイズを指定します。

参考URL

  1. Cの仕様上、char <= short <= int <= long <= long longというサイズの関係が成り立つ必要があるのと、型ごとの最低サイズが決められている(char 8bit, short 16bit, int 16bit, long 32bit, long long 64bit)という2点の縛りはあります。

  2. 実際には対象アーキテクチャを絞って書かれるCソースコードの方が多いと思います、念のため

15
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?