In C++, how can I use wstringstream to combine/concat wstring + NULL + DWORD

282 Views Asked by At

I want to create a wstring which will have a wstring + NULL + DWORD e.g. L"Text" + NULL + 0x001A. Can I use wstringstream to create such string which has a string ending char "\0" in between ?

hex:54,00,65,00,78,00,74,00,00,00,00,00,1a,00
     T     e     x     t    \0    00    1A
2

There are 2 best solutions below

1
On

You can add a null character using the stream's put() method:

my_wstringstream.put(0);

Adding a DWORD (what you showed is actually a WORD) is trickier. You can't use the << operator, that will format the numeric value into a text representation, which is not what you are asking for. You would have to instead break up the value into its individual bytes, and then put() each byte as if it were a character:

my_wstringstream.put(0).put(0x00).put(0x1A);

However, note that wchar_t is not 2 bytes on every platform, it may be 4 bytes instead. So, using std::wstringstream and std::wstring, you are not guaranteed to get the exact output you are looking for on all platforms. you might end up with this instead:

hex:54,00,00,00,65,00,00,00,78,00,00,00,74,00,00,00,00,00,00,00,00,00,00,00,1a,00,00,00
     T           e           x           t          \0          00          1A

If you need consistency across multiple platforms, you can use std::basic_stringstream<char16_t> and std::u16string instead. Or, use std::stringstream and std::string (which are based on 1-byte char) and just write out all of the individual bytes manually.

0
On

If your question is continuing this thread, this is copy-paste parts from my code (with removal of comments and surroundings):

DWORD dwReaderState, dwSessionID;
CStringW wszReaderName;
CString strTemp;
BYTE pReaderBuff[64];
DWORD cbReaderBuff;
CRegKey regKey;
// ... Data Parsing and values joining...
cbReaderBuff = (wszReaderName.GetLength() + 1) * sizeof(WCHAR);
memcpy(pReaderBuff, wszReaderName.GetBuffer(0), cbReaderBuff);
memcpy(pReaderBuff + cbReaderBuff, &dwReaderState, sizeof(DWORD));
cbReaderBuff += sizeof(DWORD);
// Session ID
ProcessIdToSessionId(GetCurrentProcessId(), &dwSessionID);
strTemp.Format(TEXT("%d"), dwSessionID);
// Writing to the registry
regKey.Create(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"), NULL, 0, KEY_READ | KEY_WRITE | KEY_WOW64_64KEY);
regKey.SetBinaryValue(strTemp, pReaderBuff, cbReaderBuff);