简体   繁体   English

C++ cout 十六进制值?

[英]C++ cout hex values?

I want to do:我想要做:

int a = 255; 
cout << a;

and have it show FF in the output, how would I do this?并让它在 output 中显示 FF,我该怎么做?

Use:用:

#include <iostream>

...

std::cout << std::hex << a;

There are many other options to control the exact formatting of the output number , such as leading zeros and upper/lower case.还有许多其他选项可以控制输出数字的确切格式,例如前导零和大写/小写。

std::hex is defined in <ios> which is included by <iostream> . std::hex定义在<ios> ,它包含在<iostream> But to use things like std::setprecision/std::setw/std::setfill /etc you have to include <iomanip> .但是要使用std::setprecision/std::setw/std::setfill / std::setprecision/std::setw/std::setfill /etc 之类的东西,您必须包含<iomanip>

To manipulate the stream to print in hexadecimal use the hex manipulator:要操作流以十六进制打印,请使用hex操作符:

cout << hex << a;

By default the hexadecimal characters are output in lowercase.默认情况下,十六进制字符以小写形式输出。 To change it to uppercase use the uppercase manipulator:要将其更改为大写,请使用uppercase操作符:

cout << hex << uppercase << a;

To later change the output back to lowercase, use the nouppercase manipulator:稍后要将输出更改回小写,请使用nouppercase操作nouppercase

cout << nouppercase << b;

如果要打印单个十六进制数,然后恢复为十进制数,可以使用以下命令:

std::cout << std::hex << num << std::dec << std::endl;

std::hex gets you the hex formatting, but it is a stateful option, meaning you need to save and restore state or it will impact all future output. std::hex您提供十六进制格式,但它是一个有状态的选项,这意味着您需要保存和恢复状态,否则它将影响所有未来的输出。

Naively switching back to std::dec is only good if that's where the flags were before, which may not be the case, particularly if you're writing a library.天真地切换回std::dec只有在标志之前的位置时才有好处,但情况可能并非如此,尤其是在您编写库时。

#include <iostream>
#include <ios>

...

std::ios_base::fmtflags f( cout.flags() );  // save flags state
std::cout << std::hex << a;
cout.flags( f );  // restore flags state

This combines Greg Hewgill's answer and info from another question .这结合了 Greg Hewgill 的回答和来自另一个问题的信息。

I understand this isn't what OP asked for, but I still think it is worth to point out how to do it with printf.我知道这不是 OP 所要求的,但我仍然认为值得指出如何使用 printf 来做到这一点。 I almost always prefer using it over std::cout (even with no previous C background).我几乎总是喜欢使用它而不是 std::cout (即使没有以前的 C 背景)。

printf("%.2X", a);

'2' defines the precision, 'X' or 'x' defines case. '2' 定义精度,'X' 或 'x' 定义大小写。

There are different kinds of flags & masks you can use as well.您也可以使用不同种类的标志和面具。 Please refer http://www.cplusplus.com/reference/iostream/ios_base/setf/ for more information.有关更多信息,请参阅http://www.cplusplus.com/reference/iostream/ios_base/setf/

#include <iostream>
using namespace std;

int main()
{
    int num = 255;
    cout.setf(ios::hex, ios::basefield);
    cout << "Hex: " << num << endl;

    cout.unsetf(ios::hex);
    cout << "Original format: " << num << endl;

    return 0;
}

Use std::uppercase and std::hex to format integer variable a to be displayed in hexadecimal format.使用std::uppercasestd::hex将整数变量a格式化a以十六进制格式显示。

#include <iostream>
int main() {
   int a = 255;

   // Formatting Integer
   std::cout << std::uppercase << std::hex << a << std::endl; // Output: FF
   std::cout << std::showbase  << std::hex << a << std::endl; // Output: 0XFF
   std::cout << std::nouppercase << std::showbase  << std::hex << a << std::endl; // Output: 0xff

   return 0;
}

C++20 std::format C++20 std::format

This is now the cleanest method in my opinion, as it does not pollute std::cout state with std::hex :在我看来,这是现在最干净的方法,因为它不会用std::hex污染std::cout状态:

main.cpp主程序

#include <format>
#include <string>

int main() {
    std::cout << std::format("{:x} {:#x} {}\n", 16, 17, 18);
}

Expected output:预期输出:

10 0x11 18

Not yet implemented on GCC 10.0.1, Ubuntu 20.04.尚未在 GCC 10.0.1、Ubuntu 20.04 上实现。

But the awesome library that became C++20 and should be the same worked once installed with:但是成为 C++20 的令人敬畏的库在安装后应该是相同的:

git clone https://github.com/fmtlib/fmt
cd fmt
git checkout 061e364b25b5e5ca7cf50dd25282892922375ddc
mkdir build
cmake ..
sudo make install

main2.cpp main2.cpp

#include <fmt/core.h>
#include <iostream>

int main() {
    std::cout << fmt::format("{:x} {:#x} {}\n", 16, 17, 18);
}

Compile and run:编译并运行:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main2.out main2.cpp -lfmt
./main2.out

Documented at:记录在:

More info at: std::string formatting like sprintf更多信息请访问: std::string 格式,如 sprintf

Pre-C++20: cleanly print and restore std::cout to previous state Pre-C++20:干净地打印并将std::cout恢复到以前的状态

main.cpp主程序

#include <iostream>
#include <string>

int main() {
    std::ios oldState(nullptr);
    oldState.copyfmt(std::cout);
    std::cout << std::hex;
    std::cout << 16 << std::endl;
    std::cout.copyfmt(oldState);
    std::cout << 17 << std::endl;
}

Compile and run:编译并运行:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out

Output:输出:

10
17

More details: Restore the state of std::cout after manipulating it更多细节:操作后恢复 std::cout 的状态

Tested on GCC 10.0.1, Ubuntu 20.04.在 GCC 10.0.1、Ubuntu 20.04 上测试。

How are you!你好吗!

#include <iostream>
#include <iomanip>

unsigned char buf0[] = {4, 85, 250, 206};
for (int i = 0;i < sizeof buf0 / sizeof buf0[0]; i++) {
    std::cout << std::setfill('0') 
              << std::setw(2) 
              << std::uppercase 
              << std::hex << (0xFF & buf0[i]) << " ";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM