在C#中,使用Socket編程時,通常需要將不同類型的數(shù)據(jù)發(fā)送和接收。為了實現(xiàn)這一點,你需要對數(shù)據(jù)進行格式轉(zhuǎn)換。以下是一些建議和方法來處理數(shù)據(jù)格式轉(zhuǎn)換:
string data = "Hello, World!";
byte[] buffer = Encoding.UTF8.GetBytes(data);
byte[] buffer = new byte[] { 72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33 };
string data = Encoding.UTF8.GetString(buffer);
int value = 12345;
byte[] buffer = BitConverter.GetBytes(value);
// 如果需要轉(zhuǎn)換為Big-Endian格式,可以使用以下代碼:
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(buffer);
}
byte[] buffer = new byte[] { 0, 0, 48, 57 };
int value = BitConverter.ToInt32(buffer, 0);
// 如果需要從Big-Endian格式轉(zhuǎn)換為本地格式,可以使用以下代碼:
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(buffer);
}
[Serializable]
public class MyData
{
public string Name { get; set; }
public int Age { get; set; }
}
// 序列化
MyData data = 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 = (MyData)bf.Deserialize(ms);
}
在處理數(shù)據(jù)格式轉(zhuǎn)換時,請確保發(fā)送方和接收方使用相同的編碼、字節(jié)順序和序列化方法。這樣可以確保數(shù)據(jù)在傳輸過程中不會出現(xiàn)錯誤或損壞。