C++ 十六进制std::string的相反顺序
我正在使用一个旧程序,需要帮助交换十六进制字符串的顺序 是的,一个字符串…如:C++ 十六进制std::string的相反顺序,c++,C++,我正在使用一个旧程序,需要帮助交换十六进制字符串的顺序 是的,一个字符串…如: string hexString = "F07D0079" string hexString2= "F07F" 我需要每个字符串看起来像: 79007DF0& 分别为7FF0 看在上帝的份上,我不知道为什么它们会被存储在字符串中,但它们确实如此。 这是一个小的endian/big-endian问题,但由于它是一个字符串,我不能使用标准函数来颠倒顺序,可以吗? 有什么简单的方法可以做到这一点吗 std::string
string hexString = "F07D0079"
string hexString2= "F07F"
我需要每个字符串看起来像:
79007DF0&
分别为7FF0
看在上帝的份上,我不知道为什么它们会被存储在字符串中,但它们确实如此。这是一个小的endian/big-endian问题,但由于它是一个字符串,我不能使用标准函数来颠倒顺序,可以吗? 有什么简单的方法可以做到这一点吗
std::string swapValues(string originalHex)
{
string swappedHex;
//what to do here.
return swappedHex;
}
我可以使用
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::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...");
}
首先检查长度是否均匀(如果尚未消毒): 然后反转字符串:
std::reverse(hex.begin(), hex.end());
现在字节的顺序是正确的,但每个字节中的数字都是错误的,因此我们需要将它们调回:
for (auto it = hex.begin(); it != hex.end(); it += 2) {
std::swap(it[0], it[1]);
}
应该有可用的库函数(简单的字符串操作可能不好):
#包括
#包括
int main(){
std::string hex32=“F07D0079”;
std::string hex16=“F07F”;
std::uint32_t u32=std::stroul(hex32.c_str(),0,16);
std::uint16_t u16=std::strtool(hex16.c_str(),0,16);
//在这里,我们需要知道源的endian。
u32=ntohl(u32);
u16=ntohs(u16);
std::cout好像没有任何stdlib函数在字符串上运行……”但由于它在字符串中,我不能使用标准函数来颠倒顺序,可以吗呃…为什么会有问题?Stl stuff与Stl容器一起工作,而string就是这样的容器。只有当ntohl
和ntoh
是编译器库的一部分时,这才有效。@ThomasMatthews当然,但这取决于平台/机器是否使用it[0]
自找麻烦?谁说它存在?为什么不改用std::iter\u swap
呢?@KerrekSB:标准说它存在(对于随机访问迭代器),相当于*(it+0)
。如果这不符合您的审美观,您可以使用iter\u swap
或其他各种替代方法。很好,我从来都不知道随机访问迭代器有[]-运算符。非常有用。
for (auto it = hex.begin(); it != hex.end(); it += 2) {
std::swap(it[0], it[1]);
}
#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';
}