簡體   English   中英

十六進制std :: string的逆序

[英]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.

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