0

Alright so I have a BYTE array that I need to ultimately convert into a LPCWSTR or const WCHAR* to use in a built in function. I have been able to print out the BYTE array with printf but now that I need to convert it into a string I am having problems... mainly that I have no idea how to convert something like this into a non array type.

BYTE ba[0x10];
for(int i = 0; i < 0x10; i++)
{
    printf("%02X", ba[i]); // Outputs: F1BD2CC7F2361159578EE22305827ECF
}

So I need to have this same thing basically but instead of printing the array I need it transformed into a LPCWSTR or WCHAR or even a string. The main problem I am having is converting the array into a non array form.

Xorty
  • 69
  • 1
  • 8
  • Converting BYTE* to string? Have you looked at [this question](http://stackoverflow.com/questions/1673445/how-to-convert-byte-to-stdstring-in-c)? – Yuchen May 10 '14 at 21:24
  • Yes I have, It didnt work though since I need to grab from each index of the BYTE array. That returns 8 numbers, none of which are in the the string that is correctly printed out. Thanks though – Xorty May 10 '14 at 21:27
  • Just use wsprintf() instead. – Hans Passant May 10 '14 at 22:29
  • That would only work if the array were already encoded as UTF-16, which the array shown here is not. – Remy Lebeau May 10 '14 at 22:29

2 Answers2

2

LPCWSTR represents a UTF-16 encoded string. The array contents you have shown are outside the 7bit ASCII range, so unless the BYTE array is already encoded in UTF-16 (the array you showed is not, but if it were, you could just use a simple type-cast), you will need to do a conversion to UTF-16. You need to know the particular encoding of the array before you can do that conversion, such as with the Win32 API MultiByteToWideChar() function, or third-party libraries like iconv or ICU, or built-in locale convertors in C++11, etc. So what is the actual encoding of the array, and where is the array data coming from? It is not UTF-8, for instance, so it has to be something else.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

Alright I got it working. Now I can convert the BYTE array to a char* var. Thanks for the help guys but the formatting wasn't a large problem in this instance. I appreciate the help though, its always nice to have some extra input.

// Helper function to convert 
Char2Hex(unsigned char ch, char* szHex)
{
    unsigned char byte[2];
    byte[0] = ch/16;
    byte[1] = ch%16;
    for(int i = 0; i < 2; i++)
    {
        if(byte[i] >= 0 && byte[i] <= 9)
        {
        szHex[i] = '0' + byte[i];
        }
        else
        szHex[i] = 'A' + byte[i] - 10;
    }
    szHex[2] = 0;
}


// Function used throughout code to convert
CharStr2HexStr(unsigned char const* pucCharStr, char* pszHexStr, int iSize)
{
    int i;
    char szHex[3];
    pszHexStr[0] = 0;
    for(i = 0; i < iSize; i++)
    {
        Char2Hex(pucCharStr[i], szHex);
        strcat(pszHexStr, szHex);
    }
}
Xorty
  • 69
  • 1
  • 8