二进制数据转换为字符串

时间:2012-06-28 16:09:50

标签: c# string binary-data

我有一大块二进制数据,其中包含具有偏移量然后是字符串的结构; 在C ++中很容易:

struct foo
{
 int offset;
 char * s;
}

void * data; 
... data is read and set
foo * header = (foo*) data;
header->s = (int)header-> + (int)data;
int len = strlen(header->s);
char* ns = new char[len+1];
strcpy(ns,header->s);

够简单...... 在C#你会怎么做? 最大的问题是我不知道字符串的长度。它被终止。

我将byte[]和IntPtr中的数据存储到内存中,但我需要一个指向该数据的字符串aa字符串(char *),我可以得到字符串的长度。

1 个答案:

答案 0 :(得分:-1)

C#是一种高级语言,使用指针对这种语言来说简直不自然。

要将数据从字节数组转换为字符串,可以使用BitConverter类:

BitConverter.ToInt32(byte_array, start index);

要将其转换为字符串,您可以使用StringBuilder类:

StringBuilder str = new StringBuilder();
// i=starting index of text
for (int i = 3; i<byte_array.Length; i++)
  str.Append(byte_array[i];

return str.ToString();

如果字符串后面有更多数据,则可以为循环byte_array[i]!=0设置停止条件,当它停止时,byte_array[i]将成为字符串终止符。保存i的值,然后您可以获取数据。

另一种方法是使用ASCIIEncoding.ASCII.GetString()方法:

ASCIIEncoding.ASCII.GetString(byte_array, start_index, bytes_count);
相关问题