如何将CStringArray数据以十六进制格式赋值到unsigned char数组
Convert CStringArray Hex Strings to unsigned char Array
Got it, let's tackle this problem step by step. You have a CStringArray named m_arrSecurityAES storing 2-character hex strings (like "00", "01", all the way to "0F"), and you need to convert each of these into their corresponding byte values (e.g., 0x00, 0x01) and populate an unsigned char private_key[16] array. Here's a robust MFC-compliant solution:
Step-by-Step Implementation
First, we'll write a helper function to handle the conversion, with error checking to avoid unexpected behavior:
#include <cstring> // For memset #include <afxwin.h> // MFC core headers (if not already included) void ConvertSecurityAESToPrivateKey(unsigned char private_key[16]) { // Initialize the output array to 0 by default memset(private_key, 0, sizeof(unsigned char) * 16); // First, validate we have exactly 16 elements (matching AES-128 key size) if (m_arrSecurityAES.GetSize() != 16) { TRACE(_T("Error: m_arrSecurityAES must contain exactly 16 hex string elements!\n")); return; } // Loop through each element in the CStringArray for (int i = 0; i < 16; ++i) { CString hexStr = m_arrSecurityAES.GetAt(i); hexStr.Trim(); // Remove any leading/trailing whitespace (just in case) // Validate the string length is exactly 2 characters if (hexStr.GetLength() != 2) { TRACE(_T("Warning: Element %d has invalid length (expected 2, got %d)\n"), i, hexStr.GetLength()); continue; } // Convert the hex string to an unsigned integer unsigned int byteValue = 0; int conversionResult = _stscanf_s(hexStr, _T("%2X"), &byteValue); // Check if conversion succeeded if (conversionResult != 1) { TRACE(_T("Warning: Failed to convert element %d ('%s') to hex\n"), i, hexStr); continue; } // Cast the integer to unsigned char and store it in the key array private_key[i] = static_cast<unsigned char>(byteValue); } }
How to Use This Function
Call the helper function wherever you need to populate your private key array, then verify the results if needed:
// Declare your private key array unsigned char private_key[16]; // Convert the CStringArray to the key array ConvertSecurityAESToPrivateKey(private_key); // Optional: Print the results to debug output for (int i = 0; i < 16; ++i) { TRACE(_T("private_key[%d] = 0x%02X\n"), i, private_key[i]); }
Key Details to Note
- Error Handling: The function includes checks for invalid array sizes, malformed string lengths, and failed conversions, using
TRACEto log warnings in debug mode. - Case Insensitivity: The
%2Xformat specifier works with both uppercase ("0F") and lowercase ("0f") hex strings. - Safety: We use
_stscanf_s(the secure version ofsscanf) to avoid buffer overflows, which is recommended for MFC applications.
内容的提问来源于stack exchange,提问作者NIKHIL
相关产品推荐
相关产品推荐

