简体   繁体   中英

Reverse order of hex std::string

I'm working with an old program and need help swapping the order of a Hex String .

Yes, a string...as in:

string hexString = "F07D0079"
string hexString2= "F07F"

I need each string to look like: 79007DF0 & 7FF0 respectively.

For the love of god i don't know why they're stored in strings, but they are.
This is a little endian/big endian issue but since it's in a string i can't use standard functions to reverse the order can I?

Is there any easy way to do this?

std::string swapValues(string originalHex)
{
  string swappedHex;
  //what to do here.
  return swappedHex;
}

First check that the length is even (if it hasn't already been sanitised):

assert(hex.length() % 2 == 0);

Then reverse the string:

std::reverse(hex.begin(), hex.end());

Now the bytes are in the correct order, but the digits within each are wrong, so we need to swap them back:

for (auto it = hex.begin(); it != hex.end(); it += 2) {
    std::swap(it[0], it[1]);
}

I might use the append member function.

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

(As an exercise in extensibility, you can make the " 2 " a parameter, too.)

If you want to do it in-place, you can use std::rotate in a loop.

I wouldn't bother with something overly clever for this:

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...");
}

There should be library functions available (a naive string manipulation might be no good):

#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/Little Endian

Any function operating on the strings must know the target platform (hence there is no general solution)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM