C++ 计算十六进制值?

发布于 2024-07-12 21:54:09 字数 96 浏览 6 评论 0原文

我想做:

int a = 255; 
cout << a;

并让它在输出中显示 FF,我该怎么做?

I want to do:

int a = 255; 
cout << a;

and have it show FF in the output, how would I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

卖梦商人 2024-07-19 21:54:09

使用:

#include <iostream>

...

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

许多其他选项来控制输出数字的精确格式,例如前导零和大写/小写。

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.

分分钟 2024-07-19 21:54:09

要操纵流以十六进制打印,请使用 hex 操纵器:

cout << hex << a;

默认情况下,十六进制字符以小写形式输出。 要将其更改为大写,请使用 uppercase 操纵器:

cout << hex << uppercase << a;

稍后要将输出更改回小写,请使用 nouppercase 操纵器:

cout << nouppercase << b;

To manipulate the stream to print in hexadecimal use the hex manipulator:

cout << hex << a;

By default the hexadecimal characters are output in lowercase. To change it to uppercase use the uppercase manipulator:

cout << hex << uppercase << a;

To later change the output back to lowercase, use the nouppercase manipulator:

cout << nouppercase << b;
渔村楼浪 2024-07-19 21:54:09

std::hex 中定义,由 包含。 但是要使用诸如 std::set precision/std::setw/std::setfill/etc 之类的东西,您必须包含

std::hex is defined in <ios> which is included by <iostream>. But to use things like std::setprecision/std::setw/std::setfill/etc you have to include <iomanip>.

已下线请稍等 2024-07-19 21:54:09

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

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

If you want to print a single hex number, and then revert back to decimal you can use this:

std::cout << std::hex << num << std::dec << std::endl;
生寂 2024-07-19 21:54:09

我知道这不是 OP 所要求的,但我仍然认为值得指出如何使用 printf 来做到这一点。 我几乎总是更喜欢使用它而不是 std::cout (即使没有以前的 C 背景)。

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

'2' 定义精度,'X' 或 'x' 定义大小写。

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. I almost always prefer using it over std::cout (even with no previous C background).

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

'2' defines the precision, 'X' or 'x' defines case.

情仇皆在手 2024-07-19 21:54:09

std::hex 为您提供十六进制格式,但它是一个有状态选项,这意味着您需要保存和恢复状态,否则它将影响所有未来的输出。

天真地切换回 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

这结合了 Greg Hewgill 的答案和另一个问题中的信息。

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.

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.

#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.

帥小哥 2024-07-19 21:54:09

C++20 std::format

在我看来,这是现在最干净的方法,因为它不会污染 std::cout 状态std::hex:

main.cpp

#include <format>
#include <string>

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

预期输出:

10 0x11 18

尚未在 GCC 10.0.1、Ubuntu 20.04 上实现。

但是这个很棒的库变成了 C++20,并且在 Ubuntu 22.04 上安装后应该是一样的:

sudo apt install libfmt-dev

或者:

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

main2.cpp

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

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

编译并运行:

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

记录在:

更多信息,请访问: std::string 格式如 sprintf

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;
}

编译并运行:

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

输出:

10
17

更多详细信息: 操作后恢复 std::cout 的状态

在 GCC 10.0.1、Ubuntu 20.04 上测试。

C++20 std::format

This is now the cleanest method in my opinion, as it does not pollute std::cout state with std::hex:

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.

But the awesome library that became C++20 and should be the same worked once installed on Ubuntu 22.04 with:

sudo apt install libfmt-dev

or:

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

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

Pre-C++20: cleanly print and restore std::cout to previous state

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

Tested on GCC 10.0.1, Ubuntu 20.04.

神仙妹妹 2024-07-19 21:54:09

在 C++23 中,您可以使用 std::print< /a> 来执行此操作:

int a = 255; 
std::print("{:X}", a);

此方法比使用 I/O 操纵器更快、更简洁,并且不会影响全局格式化状态。 您还可以打印到cout,尽管这会失去一些性能优势。

std::print 广泛使用之前,您可以使用{fmt} 库,它基于(godbolt):

fmt::print("{:X}", a);

免责声明:我我是 {fmt} 和 C++23 std::print 的作者。

In C++23 you can use std::print to do this:

int a = 255; 
std::print("{:X}", a);

This method is faster, less verbose than using I/O manipulators and doesn't affect the global formatting state. You can also print to cout although this will loose some of the perf benefits.

Until std::print is widely available you can use the {fmt} library, it is based on (godbolt):

fmt::print("{:X}", a);

Disclaimer: I am the author of {fmt} and C++23 std::print.

脸赞 2024-07-19 21:54:09

有不同种类的旗帜和旗帜。 您也可以使用面膜。 请参考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;
}

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.

#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;
}
梦冥 2024-07-19 21:54:09

你好吗!

#include <iostream>
#include <iomanip>

unsigned char arr[] = {4, 85, 250, 206};
for (const auto & elem : arr) {
    std::cout << std::setfill('0') 
              << std::setw(2) 
              << std::uppercase 
              << std::hex 
              << (0xFF & elem) 
              << " ";
}

How are you!

#include <iostream>
#include <iomanip>

unsigned char arr[] = {4, 85, 250, 206};
for (const auto & elem : arr) {
    std::cout << std::setfill('0') 
              << std::setw(2) 
              << std::uppercase 
              << std::hex 
              << (0xFF & elem) 
              << " ";
}
吹梦到西洲 2024-07-19 21:54:09

使用 std::uppercasestd::hex 格式化整型变量 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;
}

Use std::uppercase and std::hex to format integer variable a to be displayed in hexadecimal format.

#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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文