Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Managed c++/cli .net convert fixed Byte array to a String^

How do I convert a fixed byte array to a String in managed c++/cli ?
For example I have the following Byte array.

Byte byte_data[5];
byte_data[0]='a';
byte_data[1]='b';
byte_data[2]='c';
byte_data[3]='d';
byte_data[4]='e';

I have tried the following code
String ^mytext=System::Text::UTF8Encoding::UTF8->GetString(byte_data);

I get the following error:
error C2664: 'System::String ^System::Text::Encoding::GetString(cli::array<Type,dimension> ^)' : cannot convert parameter 1 from 'unsigned char [5]' to 'cli::array<Type,dimension> ^'

like image 721
Peter H Avatar asked Mar 18 '26 17:03

Peter H


2 Answers

Here is one option:

array<Byte>^ array_data = gcnew array<Byte>(5);
for(int i = 0; i < 5; i++)
    array_data[i] = byte_data[i];
System::Text::UTF8Encoding::UTF8->GetString(array_data);

Not compiled but I think you get the idea.

Or use the String constructor, as indicated by @ta.speot.is, with encoding set to System.Text::UTF8Encoding.

like image 187
rasmus Avatar answered Mar 20 '26 06:03

rasmus


Arm yourself with some knowledge about casting between pointers to signed and unsigned types and then you should be set to use String::String(SByte*, Int32, Int32). It might also pay to read the Remarks on the page, specifically around encoding.

I've reproduced the sample from the page here:

// Null terminated ASCII characters in a simple char array 
char charArray3[4] = {0x41,0x42,0x43,0x00};
char * pstr3 =  &charArray3[ 0 ];
String^ szAsciiUpper = gcnew String( pstr3 );
char charArray4[4] = {0x61,0x62,0x63,0x00};
char * pstr4 =  &charArray4[ 0 ];
String^ szAsciiLower = gcnew String( pstr4,0,sizeof(charArray4) );

// Prints "ABC abc"
Console::WriteLine( String::Concat( szAsciiUpper,  " ", szAsciiLower ) );

// Compare Strings - the result is true
Console::WriteLine( String::Concat(  "The Strings are equal when capitalized ? ", (0 == String::Compare( szAsciiUpper->ToUpper(), szAsciiLower->ToUpper() ) ? (String^)"TRUE" :  "FALSE") ) );

// This is the effective equivalent of another Compare method, which ignores case
Console::WriteLine( String::Concat(  "The Strings are equal when capitalized ? ", (0 == String::Compare( szAsciiUpper, szAsciiLower, true ) ? (String^)"TRUE" :  "FALSE") ) );
like image 40
ta.speot.is Avatar answered Mar 20 '26 05:03

ta.speot.is



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!