示例#1
0
int CCommonFnc::BYTE_ConvertFromHexStringToArray(string_type hexaString, BYTE* pArray, DWORD* pbArrayLen) {
    int         status = STAT_OK;
    DWORD       pos = 0;
    DWORD       pos2 = 0;
	string_type     hexNum;
    DWORD       num;
    BYTE*       pTempArray = NULL;
    DWORD       tempArrayPos = 0;

    // EAT SPACES
    //hexaString.TrimLeft(); hexaString.TrimRight();
	hexaString.erase(hexaString.find_last_not_of(_CONV(" ")) + 1);
	size_t startpos = hexaString.find_first_not_of(_CONV(" "));
	if (string_type::npos != startpos) {
		hexaString = hexaString.substr(startpos);
	}
    hexaString += _CONV(" ");
    hexaString.length();

    if (status == STAT_OK) {
        pTempArray = new BYTE[hexaString.length()];
        memset(pTempArray, 0, hexaString.length());

        pos = pos2 = 0;
        /*while ((pos = hexaString.Find(' ', pos2)) != -1) {
            hexNum = hexaString.Mid(pos2, pos - pos2);
            hexNum.TrimLeft(); hexNum.TrimRight();
            if (hexNum.GetLength() > 0) {
                num = strtol((LPCTSTR) hexNum, NULL, 16);
        
                if (num == 0xFF) pTempArray[tempArrayPos] = 0xFF;
                else pTempArray[tempArrayPos] = (BYTE) num & 0xFF;
                
                tempArrayPos++;
            }
            pos2 = pos + 1;
        }*/
		while ((pos = hexaString.find(' ', pos2)) != string_type::npos) {
			hexNum = hexaString.substr((pos2, pos - pos2));
			hexNum.erase(hexNum.find_last_not_of(_CONV(" ")) + 1);
			size_t startpos2 = hexNum.find_first_not_of(_CONV(" "));
			if (string_type::npos != startpos2) {
				hexNum = hexNum.substr(startpos2);
			}
			if (hexNum.length() > 0) {
				num = type_to_int((LPCTSTR)hexNum.c_str(), NULL, 16);

				if (num == 0xFF) pTempArray[tempArrayPos] = 0xFF;
				else pTempArray[tempArrayPos] = (BYTE)num & 0xFF;

				tempArrayPos++;
			}
			pos2 = pos + 1;
		}

        if (tempArrayPos > *pbArrayLen) {
            status = STAT_NOT_ENOUGHT_MEMORY;
        }  
        else {
            memcpy(pArray, pTempArray, tempArrayPos);
        }
        *pbArrayLen = tempArrayPos;

        if (pTempArray) delete[] pTempArray;
    }

    return status;
}