ストリームに4桁の固定幅の16進数を出力したい場合は、次のようにする必要があります。
cout << "0x" << hex << setw(4) << setfill('0') << 0xABC;
少し長めのようです。マクロを使用すると、次のことが役立ちます。
#define HEX(n) "0x" << hex << setw(n) << setfill('0')
cout << HEX(4) << 0xABC;
マニピュレータを組み合わせるより良い方法はありますか?
可能であれば、マクロは避けてください。それらはコードを隠し、デバッグを困難にし、スコープを尊重しないなどです。
KenEが提供する単純な関数を使用できます。あなたがすべての派手で柔軟になりたいなら、あなたはあなた自身のマニピュレーターを書くことができます:
#include <iostream>
#include <iomanip>
using namespace std;
ostream& hex4(ostream& out)
{
return out << "0x" << hex << setw(4) << setfill('0');
}
int main()
{
cout << hex4 << 123 << endl;
}
これにより、もう少し一般的になります。上記の関数を使用できる理由は、次のoperator<<
ようにすでにオーバーロードされているためですostream& operator<<(ostream&, ostream& (*funtion_ptr)(ostream&))
。endl
他のいくつかのマニピュレータもこのように実装されています。
実行時に桁数を指定できるようにする場合は、次のクラスを使用できます。
#include <iostream>
#include <iomanip>
using namespace std;
struct formatted_hex
{
unsigned int n;
explicit formatted_hex(unsigned int in): n(in) {}
};
ostream& operator<<(ostream& out, const formatted_hex& fh)
{
return out << "0x" << hex << setw(fh.n) << setfill('0');
}
int main()
{
cout << formatted_hex(4) << 123 << endl;
}
ただし、コンパイル時にサイズを決定できる場合は、関数テンプレートを使用することもできます[この提案をしてくれたJonPurdyに感謝します]。
template <unsigned int N>
ostream& formatted_hex(ostream& out)
{
return out << "0x" << hex << setw(N) << setfill('0');
}
int main()
{
cout << formatted_hex<4> << 123 << endl;
}
なぜマクロ-代わりに関数を使用できないのですか?
void write4dhex(ostream& strm, int n)
{
strm << "0x" << hex << setw(4) << setfill('0') << n;
}
std::format
C ++ 20では、これを使用して冗長性を大幅に減らすことができます。
std::cout << std::format("0x{:04x}", 0xABC);
出力:
0x0abc
フォーマット文字列を定数に格納することで、フォーマット文字列を簡単に再利用することもできます。
それまでの間、に基づいて{fmt}ライブラリを使用できます。std::format
{fmt}は、print
これをさらに簡単かつ効率的にする関数も提供します(godbolt)。
fmt::print("0x{:04x}", 0xABC);
免責事項:私は{fmt}とC++20の作者ですstd::format
。