简体   繁体   English

将C#字符串转换为C char数组

[英]Convert C# string to C char array

I am sending a string from C# to C via sockets: 我正在通过套接字将string从C#发送到C:

write 5000 100

In C, I split the received string using spaces. 在C语言中,我使用空格分割接收到的string

char **params = str_split(buffer, ' ');

And then access the 3rd parameter, and convert 100 into C char . 然后访问第3个参数,并将100转换为C char However, I need to be able to send an array of chars from C# (1 byte each) so that I can use them in C. 但是,我需要能够从C#发送一个chars array (每个chars 1 byte ),以便可以在C中使用它们。

For instance, let's say I need to send the following string: 例如,假设我需要发送以下字符串:

write 5000 <byte[] { 0x01, 0x20, 0x45 }>

Of course, the byte array needs to be transformed into string characters in C# that can be sent via StreamWriter . 当然, byte array需要转换为C#中可以通过StreamWriter发送的string字符。 StreamWriter accepts array of chars which are 2 bytes each, but I need 1 byte. StreamWriter接受每个2字节的chars array ,但是我需要1个字节。

How can this be accomplished? 如何做到这一点?

I don't quite understand your question, is it what you are looking for? 我不太了解您的问题,这是您要寻找的吗?

byte[] bytes = Encoding.UTF8.GetBytes("your string");

and vice versa 反之亦然

string text = Encoding.UTF8.GetString(bytes);

In C, char is of 1 byte size. 在C中, char为1字节大小。 Thus, to accommodate them from C#, you will need to send byte . 因此,要从C#中容纳它们,您将需要发送byte

And it seems like you need two different inputs for your problem: 看来您需要两个不同的输入来解决您的问题:

C# C#

string textFront = "write 5000"; //input 1
byte[] bytes = new byte[] { 0x01, 0x20, 0x45 }; //input 2

And then to send them together, I would rather use Stream which allows you to send byte[] . 然后将它们一起发送,我宁愿使用Stream ,它允许您发送byte[] Thus, we only need to (1) Change the textFront into byte[] , (2) concat textFront with bytes , and lastly (3) send combined variable as byte[] . 因此,我们只需要(1)改变textFrontbyte[]的concat textFrontbytes ,最后(3)发送合并的变量作为byte[]

byte[] frontBytes = Encoding.ASCII.GetBytes(textFront); // no (1)

byte[] combined = new byte[frontBytes.Length + bytes.Length];
frontBytes.CopyTo(combined, 0);
bytes.CopyTo(combined, frontBytes.Length); //no (2)

Stream stream = new StreamWriter(); //no (3)
stream.Write(combined, 0, combined.Length);

The StreamWriter constructor may receive a Encoding parameter. StreamWriter构造函数可以接收一个Encoding参数。 Maybe that's what you want. 也许这就是您想要的。

var sw = new StreamWriter(your_stream, Encoding.ASCII);
sw.Write("something");

There is also the BinaryWriter class that can write strings and byte[]. 还有BinaryWriter类,可以编写字符串和byte []。

var bw = new BinaryWriter(output_stream, Encoding.ASCII);
bw.Write("something");
bw.Write(new byte[] { 0x01, 0x20, 0x45 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM