2017-08-07 311 views
0

我有字符串十六進制ex。 std :: string x =「68656c6c6f」; 我想將它轉換爲字符數組 數組中的每個元素是2個十六進制數字 前。從十六進制字符串轉換爲十六進制字符數組

char c[5]={0x68,0x65,0x6c,0x6c,0x6f} ; 

我使用C++和我已經有十六進制數字的字符串和我沒有讀值作爲字符數組的選項。 我不能使用scanf("%x",&c[i]);

+0

你應該表現出你已經嘗試過自己,或者你有什麼研究,或爲什麼要難倒(這是相當容易出現許多可能的解決方案)。現在你的「問題」要麼是「請爲我做我的工作」或者「我需要一些關於如何做到這一點的模糊提示」,並且這兩者都不適合堆棧溢出。 – hyde

+2

另外,C或C++?他們是不同的語言。請刪除一個標籤。 'string'是C++,如果你的意思是'std :: string'。 – hyde

+0

提示:看看'std :: stoi'和類似。 –

回答

0

C(將用C工作++以及)

int cnvhex(const char *num, int *table) 
{ 
    const char *ptr; 
    int index = (num == NULL || table == NULL) * -1; 


    size_t len = strlen(num); 

    ptr = num + len - 2; 
    if (!index) 
    { 
     for (index = 0; index < len/2; index++) 
     { 
      char tmp[3] = { 0, }; 

      strncpy(tmp, ptr, 2); 
      if (sscanf(tmp, "%x", table + index) != 1) 
      { 
       index = -1; 
       break; 
      } 
      ptr -= 2; 
     } 
     if (index != -1 && (len & 1)) 
     { 
      char tmp[2] = { *num, 0}; 

      if(sscanf(tmp, "%x", table + index++) != 1) index = -1; 
     } 
    } 
    return index; 
} 
相關問題