簡體   English   中英

如何在C ++中將枚舉的十六進制值打印為字符串

[英]how to print hex value of an enum to a string in c++

如何將以下enum的十六進制值轉換為字符串並將其存儲在變量中。

enum {
    a      = 0x54,
    b,
    c
};

例如

auto value = a;
std::string value_as_hex = to_hex(a);

我如何寫to_hex

如果要打印枚舉的十六進制值,則可以將printf與%x占位符一起使用。 例如

#include <cstdio>

enum Foo {
    a      = 0x54,
    b      = 0xA6,
    c      = 0xFF
};

int main() {
    Foo e;

    e = a;
    printf("%x\n",e);

    e = b;
    printf("%x\n",e);

    e = c;
    printf("%x\n",e);

}

該程序的輸出是

54
a6
ff

以下解決方案如何?

std::ostringstream str;
str << std::hex << a;
auto x = str.str();

您可以編寫to_hex函數,以使用stringstreams和IO操作將值的十六進制表示形式存儲在字符串中:

#include <iostream>
#include <sstream>

std::string to_hex(const unsigned a) {
    std::stringstream ss;
    ss << "0x" << std::hex << a;
    return ss.str();
}

int main() {
    unsigned value = 0x1234;
    std::string value_as_hex = to_hex(value);

    std::cout << value_as_hex << "\n";
}

輸出:

0x1234

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM