在C#中,使用Socket编程时,通常需要将不同类型的数据发送和接收。为了实现这一点,你需要对数据进行格式转换。以下是一些建议和方法来处理数据格式转换:
- 字符串转字节数组(Encoding):
string data = "https://www.yisu.com/ask/Hello, World!"; byte[] buffer = Encoding.UTF8.GetBytes(data);
- 字节数组转字符串(Decoding):
byte[] buffer = new byte[] { 72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33 }; string data = https://www.yisu.com/ask/Encoding.UTF8.GetString(buffer);>
- 整数转字节数组(Big-Endian或Little-Endian):
int value = https://www.yisu.com/ask/12345;>
- 字节数组转整数(Big-Endian或Little-Endian):
byte[] buffer = new byte[] { 0, 0, 48, 57 }; int value = https://www.yisu.com/ask/BitConverter.ToInt32(buffer, 0);>
- 使用序列化和反序列化处理自定义对象:
[Serializable] public class MyData { public string Name { get; set; } public int Age { get; set; } } // 序列化 MyData data = https://www.yisu.com/ask/new MyData { Name ="John", Age = 30 }; byte[] buffer; using (MemoryStream ms = new MemoryStream()) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, data); buffer = ms.ToArray(); } // 反序列化 MyData receivedData; using (MemoryStream ms = new MemoryStream(buffer)) { BinaryFormatter bf = new BinaryFormatter(); receivedData = https://www.yisu.com/ask/(MyData)bf.Deserialize(ms);>在处理数据格式转换时,请确保发送方和接收方使用相同的编码、字节顺序和序列化方法。这样可以确保数据在传输过程中不会出现错误或损坏。