簡體   English   中英

將hex std :: string轉換為unsigned char

[英]Convert hex std::string to unsigned char

我有一個十六進制字符串,並希望將其轉換為十六進制unsigned char數組!

std::string hex = "0c45a1bf"

unsigned char hexCh = ""
    [0] = "0c"
    [1] = "45"
    [2] = "a1"
    [3] = "bf"

我想在hexCh中顯示這個優點!

串流和std :: hex的最佳方式? 你有實施嗎?!

謝謝

假設你想每對十六進制字符串的

std::string hex = "0c45a1bf";

int main(int argc, char **argv)
{
    union U
    {
        unsigned int value;
        unsigned char components[4];
    };

    U u;

    std::stringstream SS(hex);
    SS >> std::hex >> u.value;

    std::cout << u.components[0] << '\n'; // the 0c value
    std::cout << u.components[1] << '\n'; // the 45 value
    std::cout << u.components[2] << '\n'; // the a1 value
    std::cout << u.components[3] << '\n'; // the bf value
}

您可以將值讀入union並獲取每個子部分。

使用std::stringstream + std::hex

std::stringstream ss;
std::string hex = "0c45a1bf";
std::vector<unsigned char> hexCh;
unsigned int buffer;
int offset = 0;
while (offset < hex.length()) {
   ss.clear();
   ss << std::hex << hex.substr(offset, 2);
   ss >> buffer;
   hexCh.push_back(static_cast<unsigned char>(buffer));
   offset += 2;
}

您可以將整個字符串轉換為更大的整數類型,並從中選擇字節。 就像是:

std::vector<unsigned char>
asBytes( std::string const& input )
{
    std::istringstream parser( input );
    uint32_t tmp;
    input >> std::hex >> tmp;
    std::vector<unsigned char> results;
    //  The conversion implicitly does the & 0xFF
    results.push_back( tmp >> 24 );
    results.push_back( tmp >> 16 );
    results.push_back( tmp >>  8 );
    results.push_back( tmp       );
    return results;
}

或者,您可以創建每個兩個字符的子字符串,為每個字符創建一個std::istringstream ,並從中輸入。 你仍然需要輸入一個大於char的類型,因為>>到一個字符類型只讀取一個字符,然后分配它。 但是你可以把它讀成int ,然后將int轉換為unsigned char

unsigned char
convertOneByte( std::string::const_iterator begin,
                std::string::const_iterator end )
{
    std::istringstream parser( std::string( begin, end ) );
    int tmp;
    parser >> std::hex >> tmp;
    return tmp;
}

std::vector<unsigned char>
asBytes( std::string const& input )
{
    std::vector<unsigned char> results;
    results.push_back( input.begin()    , input.begin() + 2 );
    results.push_back( input.begin() + 2, input.begin() + 4 );
    results.push_back( input.begin() + 4, input.begin() + 6 );
    results.push_back( input.begin() + 6, input.begin() + 8 );
    return results;
}

(這兩段代碼都需要更多的錯誤檢查。它們只是為了給你一個想法。)

這2個功能一起完成工作:

這個很簡單:

inline int char2hex(char c)
{
   if (c >= '0' && c <= '9') return c - '0';
   if (c >= 'a' && c <= 'f') return c - 'a' + 10;
   if (c >= 'A' && c <= 'F') return c - 'A' + 10;
   throw std::runtime_error("wrong char");
}

這有點復雜:

std::vector<unsigned char> str2hex(const std::string& hexStr)
{
     std::vector<unsigned char> retVal;
     bool highPart = ((hexStr.length() % 2) == 0);  
     // for odd number of characters - we add an extra 0 for the first one:
     if (!highPart)
         retVal.push_back(0);
     std::for_each(hexStr.begin(), hexStr.end(), 
        [&](char nextChar) {
           if (highPart) 
               // this is first char for the given hex number:
               retVal.push_back(0x10 * char2hex(nextChar));
           else
              // this is the second char for the given hex number
              retVal.back() += char2hex(nextChar);
           highPart = !highPart;
       }
     );

    return retVal;
}

以及它的工作示例

int main() {
  std::string someHex =  "c45a1bf";
  std::vector<unsigned char> someUHex = str2hex(someHex);
  std::copy(someUHex.begin(), someUHex.end(), std::ostream_iterator<int>(std::cout << std::hex, ""));
}

一個可能的解決方案:( thx Denis Ermolin):

void ClassA::FuncA(unsigned char *answer)
{
    std::string hex = "0c45a1bf";
    std::stringstream convertStream;

    // if you have something like "0c 45 a1 bf" -> delete blanks
    hex.erase( std::remove(hex.begin(), hex.end(), ' '), hex.end() );

    int offset = 0, i = 0;      
    while (offset < hex.length()) 
    {
        unsigned int buffer;

        convertStream << std::hex << hex.substr(offset, 2);         
        convertStream >> std::hex >> buffer;

        answer[i] = static_cast<unsigned char>(buffer);

        offset += 2;
        i++;

        // empty the stringstream
        convertStream.str(std::string());
        convertStream.clear();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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