隨手在網上找了一段將字節數組轉換爲十六進制字符串的代碼,結果被坑慘了

博文連接:c++

c++ byte類型數組轉十六進制字符串的幾種代碼實現數組

如下是我根據博文修改格式出來的一個方法:socket

string* byteArray2HexStr(char* charArr, int len) {
    string* strRetVal = new string();
    
    for (int i = 0; i < len; i ++) {
        char char1;
        char char2;
        
        int iVal = charArr[i];
        int iVal1 = iVal / 16;
        int iVal2 = iVal % 16;
        
        if (iVal1 >= 0 && iVal1 <= 9) {
            char1 = (char)(48 + iVal1);
        } else {
            char1 = (char)(55 + iVal1);
        }
        
        if (iVal2 >= 0 && iVal2 <= 9) {
            char2 = (char)(48 + iVal2);
        } else {
            char2 = (char)(55 + iVal2);
        }
        
        *strRetVal = *strRetVal + char1 + char2;
    }
    
    return strRetVal;
}
剛找到這個東西的時候仍是挺開心的,想到之後調試數據會方便些了。

沒想到昨天在調一個 bug 的時候居然中招了。測試

活生生將一個字節數組轉換成了錯誤的十六進制字符串,而後我在作數據對比的時候,讓我懷疑是在 bsd socket 的 recv() 方法出現了問題。spa

還特地發了一個帖子去向別人請教這個異常奇葩的問題:.net

bsd socket 接收緩衝長度不夠時接收出錯的問題調試

詳情請看帖子,其餘就很少吐槽了,下面給出一個 「不可靠」 的例證:code

#include <string>
#include <stdio.h>
#include "HexUtil.h"

using namespace std;

/**
 * 執行結果爲:
 * e3 轉換結果爲:6*
 */
int main(int argc, const char * argv[]) {
    
    int i = 0xE3;
    
    unsigned char t_pArrChar[1];
    t_pArrChar[0] = (unsigned char)i;
    
    string* str = byteArray2HexStr(t_pArrChar, 1);
    
    printf("%x 轉換結果爲:%s\n", i, str->c_str());
}
最後,總結一下:

網上現成的東西,本身拿過來用以前,要記得先作一下測試,檢驗一下牢固程度。blog

相關文章
相關標籤/搜索