[英]Does C++ std::hex reverse bytes order? (printing decimal as hexadecimal)
[英]Reverse order of hex std::string
我正在使用旧程序,需要帮助来交换十六进制字符串的顺序 。
是的,一个字符串...如:
string hexString = "F07D0079"
string hexString2= "F07F"
我需要每个字符串分别如下所示:79007DF0和7FF0。
对于上帝的爱,我不知道为什么将它们存储在字符串中,但是它们却是。
这是一个小字节序/大字节序的问题,但是由于它是字符串形式的,所以我不能使用标准函数来颠倒顺序,可以吗?
有没有简单的方法可以做到这一点?
std::string swapValues(string originalHex)
{
string swappedHex;
//what to do here.
return swappedHex;
}
首先检查该长度是否为偶数(如果尚未清除):
assert(hex.length() % 2 == 0);
然后反转字符串:
std::reverse(hex.begin(), hex.end());
现在字节的顺序正确,但是每个字节中的数字是错误的,因此我们需要将它们交换回去:
for (auto it = hex.begin(); it != hex.end(); it += 2) {
std::swap(it[0], it[1]);
}
我可能会使用append
成员函数。
std::string reverse_pairs(std::string const & src)
{
assert(src.size() % 2 == 0);
std::string result;
result.reserve(src.size());
for (std::size_t i = src.size(); i != 0; i -= 2)
{
result.append(src, i - 2, 2);
}
return result;
}
(作为可扩展性的练习,您也可以将“ 2
”作为参数。)
如果要就地执行此操作,则可以在循环中使用std::rotate
。
对于这一点,我不会太过聪明:
std::string swapValues(const std::string& o)
{
std::string s(o.length());
if (s.length() == 4) {
s[0] = o[2];
s[1] = o[3];
s[2] = o[0];
s[3] = o[1];
return s;
}
if (s.length() == 8) {
// left as an exercise
}
throw std::logic_error("You got to be kidding me...");
}
应该有可用的库函数(单纯的字符串操作可能不好):
#include <iostream>
#include <arpa/inet.h>
int main() {
std::string hex32 = "F07D0079";
std::string hex16 = "F07F";
std::uint32_t u32 = std::strtoul(hex32.c_str(), 0, 16);
std::uint16_t u16 = std::strtoul(hex16.c_str(), 0, 16);
// Here we would need to know the endian of the sources.
u32 = ntohl(u32);
u16 = ntohs(u16);
std::cout << std::hex << u32 << ", " << u16 << '\n';
}
Linux /小端
在字符串上运行的任何函数都必须知道目标平台(因此没有通用解决方案)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.