分享

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

 羊玉wngbx 2019-06-22

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

girl模型有四个信息,GetByteNets方法将信息转化为字节流,GetGirlFormNets()方法展示如何将字节流转化为信息

  1. using System;
  2. public class Girl
  3. {
  4. byte sex;
  5. short height;
  6. float weight;
  7. int age;
  8. public byte[] GetByteNets() //将这个对象转化为字节流
  9. {
  10. //表示偏移量
  11. int offset = 0;
  12. //输出的字节流
  13. byte[] result= new byte[11];
  14. //第一个字节放入数组
  15. result[0] = sex;
  16. offset++;
  17. //将身高参数转化为字节流(short转字节流)
  18. byte[] heightBytes = BitConverter.GetBytes(this.height);
  19. //字节流拷贝(源字节流,从第0个开始拷贝,目标字节流,拷贝到目标字节流第offset个,拷贝长度为原字节流长度)
  20. Buffer.BlockCopy(heightBytes,0,result,offset,heightBytes.Length);
  21. offset += heightBytes.Length;
  22. //将体重参数转化为字节流
  23. byte[] weightBytes = BitConverter.GetBytes(this.weight);
  24. //字节流拷贝
  25. Buffer.BlockCopy(weightBytes, 0, result, offset, weightBytes.Length);
  26. offset += weightBytes.Length;
  27. //将年龄转化为字节流
  28. byte[] ageBytes = BitConverter.GetBytes(this.age);
  29. //字节流拷贝
  30. Buffer.BlockCopy(ageBytes, 0, result, offset, ageBytes.Length);
  31. offset += ageBytes.Length;
  32. return result;
  33. }
  34. public Girl GetGirlFromNet(byte[] buffer) //输入字节流 输出对象
  35. {
  36. Girl result = new Girl();
  37. result.sex = buffer[0];
  38. result.height = BitConverter.ToInt16(buffer, 1);
  39. result.weight = BitConverter.ToSingle(buffer, 3);
  40. result.age = BitConverter.ToInt32(buffer, 7);
  41. return result;
  42. }
  43. }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多