Archived

This topic is now archived and is closed to further replies.

TheMatrixXXX

AnsiString to byte

Recommended Posts

TheMatrixXXX    122
hi can anyone tell me how to store an AnsiString in a byte array? the source:
  
AnsiString funcname(AnsiString s)
{
  byte barray[] = ??
  //what i have to do now?


}
  
thx --=[[TheMatrixXXX]]=--

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
<source>
AnsiString funcname(AnsiString s)
{ int StringByteSize;
int StringLength;
BYTE *pByteArray;

// Calculate the strings length and add in an extra space for the ''\0''.
StringLength = strlen(s) + 1;

//Calculate the number of bytes in the string.
StringByteSize = ( StringLength * sizeof(BYTE) );

// Create our dynamic array of bytes.
pByteArray = new BYTE[StringByteSize];

// Shows you how to access the data in the array.
for(int i=0; i < StringLength; i++)
{
// Output the BYTE.
cout << (BYTE)pByteArray[StringLength];
}
cout << endl;

// Free up the dynamic memory we allocated.
delete [] pByteArray;

}
</source>

Share this post


Link to post
Share on other sites
Cirian    122
No way you can do it in a static array... but here is a slighly more BCB style version of anon's answer...

      
void funcname(AnsiString s)
{
unsigned char *barray = new unsigned char[s.Length()+1];
memcpy((void *)barray, s.data(), s.Length()+1);
delete[] barray;
}


Note that "BYTE" is unsigned char in BCB -- yet all string data is signed.... so not sure what will happen.....

Edit: added byte/uchar info
Edit: changed return to void

Edited by - Cirian on January 15, 2002 8:50:48 PM

Share this post


Link to post
Share on other sites