提问人:Dan 提问时间:9/27/2023 更新时间:9/27/2023 访问量:99
如何让我的十六进制字符串在 C++ 中包含中间零?
How do I get my Hex String to include intermediate zeroes in C++?
问:
我正在尝试将存储为字节向量的 UUID 输出为带有破折号的十六进制字符串。当任何单个字节具有前导零时,我的输出字符串会跳过它。我正在使用 std::setw(2) 并且仍然得到这种行为。
我尝试了以下代码:
#include <iomanip>
#include <iostream>
std::ostream& operator<<(std::ostream &os, const Id &id) {
std::ios oldState(nullptr);
oldState.copyfmt(os);
os << std::hex << std::uppercase << std::setfill('0') << std::setw(2);
for (int i = 0; i < 16; i++) {
os << (int)id.id_[i];
if (i == 3 || i == 5 || i == 7 || i == 9) os << '-';
}
os.copyfmt(oldState);
return os;
}
我的预期输出是这样的:
01020304-0102-0304-0506-AA0F0E0D0C0B
相反,我得到:
1234-12-34-56-AAFEDCB
我显然在这里做错了什么。我尝试在事后刷新缓冲区并插入破折号,但仍然没有运气。
答:
1赞
tbxfreeware
9/27/2023
#1
正如评论中所解释的那样,是一次性操纵器。它仅适用于下一个输出项。之后,流宽度重置为 0。std::setw
解决方法很简单:进入循环。setw
出于演示目的,我创建了 .struct Id
// main.cpp
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
#include <initializer_list>
struct Id
{
Id(std::initializer_list<std::uint8_t> l)
: id_{ l }
{}
std::vector<std::uint8_t> id_;
};
std::ostream& operator<<(std::ostream& os, const Id& id) {
std::ios oldState(nullptr);
oldState.copyfmt(os);
os << std::hex << std::uppercase << std::setfill('0');
for (int i = 0; i < 16; i++) {
os << std::setw(2) << (int)id.id_[i]; // <===== setw goes here
if (i == 3 || i == 5 || i == 7 || i == 9) os << '-';
}
os.copyfmt(oldState);
return os;
}
int main()
{
Id id{
0x01, 0x02, 0x03, 0x04, 0x01, 0x02, 0x03, 0x04,
0x05, 0x06, 0xAA, 0x0F, 0x0E, 0x0D, 0x0C, 0x0B
};
std::cout << id << '\n';
return 0;
}
输出:
01020304-0102-0304-0506-AA0F0E0D0C0B
0赞
Jakkapong Rattananen
9/27/2023
#2
我认为用于转换的创建函数然后在重载中调用它更可重用。
这里代码
#include <cstdint>
#include <iostream>
#include <array>
#include <string>
struct Id
{
std::array<uint8_t, 16> bytes;// std::array is same as normal array but more useful feature.
};
std::string uuid2rfc4122(const Id& uuid)
{
static char char2hex_table[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
std::string str;
str.reserve(36);//this prevent for reallocate memory from push_back
int pos = 0;
for (auto byte : uuid.bytes) { //this intend to do not use reference. Reference is actually pointer so their size is 8 bytes in 64bit system. it has overhead if we store reference pointer instead of value.
//1 byte represent by 2 hex character
str.push_back(char2hex_table[byte >> 4]); //0b1111'xxxx We don't need x. After shift value = 0b1111
str.push_back(char2hex_table[byte & 0x0f]);//0bxxxx'1111 After bitwiseAnd value = 0b0000'1111
++pos;
if (pos == 4 || pos == 6 || pos == 8 || pos == 10) {
str.push_back('-');
}
}
return str;
}
std::ostream& operator<<(std::ostream& os, const Id& id) {
os << uuid2rfc4122(id);
return os;
}
评论
setw
os << std::setw(2) << static_cast<int>(id.id_[i]);