托管c ++ / cli .net将固定的Byte数组转换为String ^

时间:2013-01-28 01:50:37

标签: c++ .net bytearray command-line-interface

如何将固定字节数组转换为托管c ++ / cli中的字符串?
例如,我有以下字节数组。

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

我试过以下代码
String ^mytext=System::Text::UTF8Encoding::UTF8->GetString(byte_data);

我收到以下错误:
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> ^'

3 个答案:

答案 0 :(得分:2)

这是一个选项:

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);

没有编译,但我认为你明白了。

或者使用String构造函数,如@ ta.speot.is所示,编码设置为System.Text::UTF8Encoding

答案 1 :(得分:2)

Arm yourself with some knowledge about casting between pointers to signed and unsigned types然后您应该设置为使用String::String(SByte*, Int32, Int32)。阅读页面上的备注也可能需要付费,特别是在编码方面。

我已经从页面上复制了样本:

// 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") ) );

答案 2 :(得分:0)

对于那些对其他工作解决方案感兴趣的人。我使用了ta.speot.is的笔记并开发了一个工作解决方案,你应该可以使用这个解决方案或Rasmus提供的解决方案。

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

char *pstr3 =  reinterpret_cast<char*>(byte_data);
String^ example1 = gcnew String( pstr3 );//Note: This method FAILS if the string is not null terminated
                                        //After executing this line the string contains garbage on the end example1="abcde<IqMŸÖð"

String^ example2 = gcnew String( pstr3,0,sizeof(byte_data));    //String Example 2 correctly contains the expected string even if it isn't null terminated