C# 基本数据类型与字节流转换

联网游戏的信息传输都是以字节流(字节数组)形式传输数据,本文展示基本数据类型与字节流互相转换

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;
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值