73

如何使用 cout 打印 0x0a 而不是 0xa?

#include  <iostream>

using std::cout;  
using std::endl;  
using std::hex;

int main()  
{  
    cout << hex << showbase << 10 << endl;  
}
4

9 回答 9

122

这在 GCC 中对我有用:

#include  <iostream>
#include  <iomanip>

using namespace std;

int main()
{
    cout << "0x" << setfill('0') << setw(2) << right << hex << 10 << endl;
}

如果您厌倦了 iostream 的格式怪异,请尝试Boost.Format 。它允许使用老式的 printf 样式的格式说明符,但它是类型安全的。

#include <iostream>
#include <boost/format.hpp>

int main()
{
    std::cout << boost::format("0x%02x\n") % 10;
}

更新(2019)

查看已被C++20接受的{fmt} 库。基准测试表明它比 Boost.Format 更快。

#if __has_include(<format>)
    #include <format>
    using std::format;
#else
    #include <fmt/format.h>
    using fmt::format;
#endif

std::cout << format("{:#04x}\n", 10);
于 2011-04-22T21:53:37.167 回答
25

使用iomanip中的setwsetfill

#include  <iostream>
#include  <iomanip>

using std::cout;  
using std::endl;  
using std::hex;

int main()
{
    cout << "0x" << std::setfill('0') << std::setw(2) << hex << 10 << endl;
}

就个人而言,iostreams 的状态性质总是让我烦恼。我认为提升格式是一个更好的选择,所以我推荐了另一个答案。

于 2011-04-22T21:30:37.697 回答
9

如果你想用一种更简单的方法来输出一个十六进制数,你可以写一个这样的函数:

更新版本如下所示;有两种0x插入基本指示符的方法,脚注详细说明了它们之间的区别。原始版本保留在答案的底部,以免给使用它的任何人带来不便。

请注意,更新版本和原始版本都可能需要针对字节大小为 9 位的倍数的系统进行一些调整。

#include <type_traits> // For integral_constant, is_same.
#include <string>      // For string.
#include <sstream>     // For stringstream.
#include <ios>         // For hex, internal, [optional] showbase.
                       // Note: <ios> is unnecessary if <iostream> is also included.
#include <iomanip>     // For setfill, setw.
#include <climits>     // For CHAR_BIT.

namespace detail {
    constexpr int HEX_DIGIT_BITS = 4;
    //constexpr int HEX_BASE_CHARS = 2; // Optional.  See footnote #2.

    // Replaced CharCheck with a much simpler trait.
    template<typename T> struct is_char
      : std::integral_constant<bool,
                               std::is_same<T, char>::value ||
                               std::is_same<T, signed char>::value ||
                               std::is_same<T, unsigned char>::value> {};
}

template<typename T>
std::string hex_out_s(T val) {
    using namespace detail;

    std::stringstream sformatter;
    sformatter << std::hex
               << std::internal
               << "0x"                                             // See footnote #1.
               << std::setfill('0')
               << std::setw(sizeof(T) * CHAR_BIT / HEX_DIGIT_BITS) // See footnote #2.
               << (is_char<T>::value ? static_cast<int>(val) : val);

    return sformatter.str();
}

它可以按如下方式使用:

uint32_t       hexU32 = 0x0f;
int            hexI   = 0x3c;
unsigned short hexUS  = 0x12;

std::cout << "uint32_t:       " << hex_out_s(hexU32) << '\n'
          << "int:            " << hex_out_s(hexI)   << '\n'
          << "unsigned short: " << hex_out_s(hexUS)  << std::endl;

实时查看这两个选项(详见下面的脚注):这里

脚注:

  1. 此行负责显示基础,可以是以下任何一种:

    << "0x"
    << std::showbase
    
    • 对于尝试输出负十六进制数 as-0x##而不是 as的自定义类型,第一个选项将显示不正确<complement of 0x##>,符号显示在基数 (as 0x-##) 之后而不是之前。这很少是一个问题,所以我个人更喜欢这个选项。

      如果这是一个问题,那么在使用这些类型时,您可以在输出基数之前检查负性,然后使用abs()(或返回无符号值的自定义abs(),如果您需要能够处理 2 上的最负值补系统)上val

    • 第二个选项将省略 base when val == 0,显示(例如,for int,其中int32 位)0000000000而不是预期的0x00000000。这是由于showbase标志在内部被视为printf()'#修饰符。

      如果这是一个问题,您可以检查是否val == 0,并在出现时应用特殊处理。

  2. 根据选择用于显示基础的选项,需要更改两行。

    • 如果使用<< "0x", thenHEX_BASE_CHARS是不必要的,可以省略。
    • 如果使用<< std::showbase,则提供给的值setw()需要考虑到这一点:

      << std::setw((sizeof(T) * CHAR_BIT / HEX_DIGIT_BITS) + HEX_BASE_CHARS)
      

原始版本如下:

// Helper structs and constants for hex_out_s().
namespace hex_out_helper {
    constexpr int HEX_DIGIT_BITS = 4; // One hex digit = 4 bits.
    constexpr int HEX_BASE_CHARS = 2; // For the "0x".

    template<typename T> struct CharCheck {
        using type = T;
    };

    template<> struct CharCheck<signed char> {
        using type = char;
    };

    template<> struct CharCheck<unsigned char> {
        using type = char;
    };

    template<typename T> using CharChecker = typename CharCheck<T>::type;
} // namespace hex_out_helper


template<typename T> std::string hex_out_s(T val) {
    using namespace hex_out_helper;

    std::stringstream sformatter;
    sformatter << std::hex
               << std::internal
               << std::showbase
               << std::setfill('0')
               << std::setw((sizeof(T) * CHAR_BIT / HEX_DIGIT_BITS) + HEX_BASE_CHARS)
               << (std::is_same<CharChecker<T>, char>{} ? static_cast<int>(val) : val);
    return sformatter.str();
}

然后可以这样使用:

uint32_t       hexU32 = 0x0f;
int            hexI   = 0x3c;
unsigned short hexUS  = 0x12;

std::cout << hex_out_s(hexU32) << std::endl;
std::cout << hex_out_s(hexI) << std::endl;
std::cout << "And let's not forget " << hex_out_s(hexUS) << std::endl;

工作示例:这里

于 2016-03-12T21:08:26.130 回答
4

在 C++20 中,您将能够使用它std::format来执行此操作:

std::cout << std::format("{:02x}\n", 10);  

输出:

0a

同时你可以使用基于的 {fmt}std::format。{fmt} 还提供了print使这更容易和更高效的功能(godbolt):

fmt::print("{:02x}\n", 10); 

免责声明:我是 {fmt} 和 C++20 的作者std::format

于 2021-03-03T01:56:20.787 回答
3

缺少答案的重要一点是您必须right与上述所有标志一起使用:

cout<<"0x"<<hex<<setfill('0')<<setw(2)<<right<<10;
于 2015-10-16T11:34:56.743 回答
1

试试这个..您只需根据幅度添加零。

cout << hex << "0x" << ((c<16)?"0":"") << (static_cast<unsigned int>(c) & 0xFF) << "h" << endl;

您可以轻松地修改它以使用更大的数字。

cout << hex << "0x";
cout << ((c<16)?"0":"") << ((c<256)?"0":"");
cout << (static_cast<unsigned int>(c) & 0xFFF) << "h" << endl;

因子为 16(对于一个十六进制数字):
16、256、4096、65536、1048576、..
分别为
0x10、0x100、0x1000、0x10000、0x100000、..

因此你也可以这样写..

cout << hex << "0x" << ((c<0x10)?"0":"") << ((c<0x100)?"0":"") << ((c<0x1000)?"0":"") << (static_cast<unsigned int>(c) & 0xFFFF) << "h" << endl;

等等.. :P

于 2014-08-19T13:24:55.930 回答
1

为了缩短输出十六进制的时间,我做了一个简单的宏

#define PADHEX(width, val) setfill('0') << setw(width) << std::hex << (unsigned)val

然后

cout << "0x" << PADHEX(2, num) << endl;
于 2017-02-24T23:46:16.530 回答
0
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    /*This should print out 0x0a. The internal adjustment pads the width with the fill character*/
    cout << hex << showbase << internal << setfill('0') << setw(4) << 10 << endl;
}
于 2020-11-08T11:09:21.523 回答
0

使用自动填充“0”或设置将任何数字打印为十六进制。模板允许任何数据类型(例如 uint8_t)

template<typename T, typename baseT=uint32_t> struct tohex_t {
    T num_;
    uint32_t width_;
    bool showbase_;

    tohex_t(T num, bool showbase = false, uint32_t width = 0) { num_ = num; showbase_ = showbase; width_ = width; }
    friend std::ostream& operator<< (std::ostream& stream, const tohex_t& num) {
        uint32_t w;
        baseT val;

        if (num.showbase_)
            stream << "0x";

        if (num.width_ == 0) {
            w = 0;
            val = static_cast<baseT>(num.num_);
            do { w += 2; val = val >> 8; } while (val > 0);
        }
        else {
            w = num.width_;
        }
        stream << std::hex << std::setfill('0') << std::setw(w) << static_cast<baseT>(num.num_);

        return stream;
    }
};
template<typename T> tohex_t<T> TO_HEX(T const &num, bool showbase = false, uint32_t width = 0) { return tohex_t<T>(num, showbase, width); }

例子:

std::stringstream sstr;
uint8_t ch = 91;
sstr << TO_HEX(5) << ',' << TO_HEX(ch) << ',' << TO_HEX('0') << std::endl;
sstr << TO_HEX(1, true, 4) << ',' << TO_HEX(15) << ',' << TO_HEX(-1) << ',';
sstr << TO_HEX(513) << ',' << TO_HEX((1 << 16) + 3, true);
std::cout << sstr.str();

输出:

05,5b,30
0x0001,0f,ffffffff,0201,0x010003
于 2018-02-21T03:03:03.000 回答