联网游戏的信息传输都是以字节流(字节数组)形式传输数据,本文展示基本数据类型与字节流互相转换
girl模型有四个信息,GetByteNets方法将信息转化为字节流,GetGirlFormNets()方法展示如何将字节流转化为信息
using System;
public class Girl
{
byte sex;
short height;
float weight;
int age;
public byte[] GetByteNets() //将这个对象转化为字节流
{
//表示偏移量
int offset = 0;
//输出的字节流
byte[] result= new byte[11];
//第一个字节放入数组
result[0] = sex;
offset++;
//将身高参数转化为字节流(short转字节流)
byte[] heightBytes = BitConverter.GetBytes(this.height);
//字节流拷贝(源字节流,从第0个开始拷贝,目标字节流,拷贝到目标字节流第offset个,拷贝长度为原字节流长度)
Buffer.BlockCopy(heightBytes,0,result,offset,heightBytes.Length);
offset += heightBytes.Length;
//将体重参数转化为字节流
byte[] weightBytes = BitConverter.GetBytes(this.weight);
//字节流拷贝
Buffer.BlockCopy(weightBytes, 0, result, offset, weightBytes.Length);
offset += weightBytes.Length;
//将年龄转化为字节流
byte[] ageBytes = BitConverter.GetBytes(this.age);
//字节流拷贝
Buffer.BlockCopy(ageBytes, 0, result, offset, ageBytes.Length);
offset += ageBytes.Length;
return result;
}
public Girl GetGirlFromNet(byte[] buffer) //输入字节流 输出对象
{
Girl result = new Girl();
result.sex = buffer[0];
result.height = BitConverter.ToInt16(buffer, 1);
result.weight = BitConverter.ToSingle(buffer, 3);
result.age = BitConverter.ToInt32(buffer, 7);
return result;
}
}
最后
以上就是虚心哑铃最近收集整理的关于C# 基本数据类型与字节流转换的全部内容,更多相关C#内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复