BYTE数组与16进制字符串互转

时间:2022-11-12 17:51:11
//字节数组转换为HEX 字符串
const
string Byte2HexString(const unsigned char* input, const int datasize) { char output[datasize*2]; for(int j = 0; j < datasize; j++ ) { unsigned char b = *(input+j); snprintf( output+j * 2,3, "%02x",b); } return string(output) ; }
/*
* 把16进制字符串转换成字节数组 @param hex @return
*/
unsigned char* HexString2Byte(string hex)
{
    int len = (hex.length() / 2);
    unsigned char* result = new unsigned char[len];
    //const char* achar = hex.c_str();
    for (int i = 0; i < len; i++) {
        int pos = i * 2;

        QString lStr(hex[pos]);
        int iLeft = lStr.toInt(NULL, 16);

        QString rStr(hex[pos+1]);
        int iRight = rStr.toInt(NULL, 16);

        int iNew = ( iLeft<< 4 | iRight);
        result[i] = (unsigned char) iNew;
    }
    return result;
}

 

调用演示:

BYTE face_feature[2560];

//16进制字符串转换为字节数组
unsigned char* pFeature = HexString2Byte(strFeature);
    memcpy(face_feature, pFeature, strFeature.length()/2);

//字节数组转换为16进制字符串
string strFeature = Byte2HexString(face_feature,2560);