Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a string say
BSTR bstrString="Arun";

I have a byte Array say
BYTE bytArray[5];

So, how to place this BSTR into BYTE* array?
Posted
Updated 14-Mar-16 16:28pm
v3

IF you are using ATL and/or MFC the easiest way is the following:

C++
CStringA ansiString(bstrString);
strncpy(bytArray, ansiString, _countof(bytArray));
 
Share this answer
 
What do you mean with 'place'?
You may copy the characters this way
BSTR bstrString= SysAllocString(L"Arun");
UINT len = SysStringLen(bstrString);
BYTE * bytArray = new BYTE[len];
int i;

for (i=0; i<len; i++)
{
   bytArray[i] = (BYTE) bstrString[i];
}
//..
// don't forget the cleanup
delete [] bytArray;


However the above code forces 16-bit values into 8 bit ones.
 
Share this answer
 
Proposed soultions are good ,however the proposed solutions doesn't work properly if the byte array taken for chinese characters or other languages as each language has different code point and encoding style to interpret the characters .Please refer to this page
[^]

My solution is to use WideCharToMultiByte which works for all the unicode characters like chineese or others as well english as we have different code pages for each language . In below sample ,cp is set as UTF-8 encoding is the default standard used to convert to byte array

BSTR bstr=L"Arun";

// The same works if the same thing is written as arun in chinese

BSTR bstr=L"阿伦";

int res = WideCharToMultiByte(cp, 0, bstr, -1, NULL, 0, NULL, NULL);
if (res > 0)
{
BYTE * bytArray = new BYTE[res ];

WideCharToMultiByte(cp, 0, bstr, -1, &bytArray [0], res, NULL, NULL);
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900