字节流

作者: MYves | 来源:发表于2019-04-02 00:23 被阅读0次

1.基本数据类型

  • 整型

    • byte 1字节 8bit
    • short 2字节
    • int 4字节
    • long 32位机器 4字节 64位机器 8字节
  • 浮点型

    • float 4字节 小数点后6-7位
    • double 8字节 小数点后15-16位
    • decimal
  • bool 1字节

  • char java/C# 2字节 C/C++ 1字节

  • GBK 包含所有的亚洲字体库

  • UTF-8 1-4字节

2. 类转字节流

  • MMORPG: C/S 架构, 状态同步, 绝大部分数据都来自服务器
  • Moba: 帧同步
  • 网络通信的时候: 必须是字节流
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CPractice : MonoBehaviour
{
    private void Start()
    {
        Person p = new Person();

        byte[] pBytes = p.ConvertToBytes();

        Person xiaoming = new Person();
        xiaoming.ConvertFromBytes(pBytes);

        Debug.Log(xiaoming);
    }
}

public class Person
{
    public byte age;        // 1byte
    public bool sex;        // true 男 false 女 1byte
    public short height;    // 2byte
    public float weight;    // 4byte

    public Person()
    {
        age = 18;
        sex = false;
        height = 165;
        weight = 100;
    }

    /// <summary>
    /// 将类变成二进制流
    /// </summary>
    /// 从上到下依次存
    /// <returns>The to bytes.</returns>
    public byte[] ConvertToBytes()
    {
        byte[] result = new byte[8];
        byte tmpOffset = 0;

        result[0] = age;
        tmpOffset += 1;

        byte[] sexBytes = BitConverter.GetBytes(sex);
        result[1] = sexBytes[0];
        tmpOffset += 1;

        byte[] heightBytes = BitConverter.GetBytes(height);
        Buffer.BlockCopy(heightBytes, 0, result, tmpOffset, heightBytes.Length);    // 相当于C/C++中的memcpy
        tmpOffset += (byte)heightBytes.Length;

        byte[] weightBytes = BitConverter.GetBytes(weight);
        Buffer.BlockCopy(weightBytes, 0, result, tmpOffset, weightBytes.Length);

        return result;
    }

    /// <summary>
    /// 将二进制流转成类
    /// </summary>
    /// <param name="buffer">Buffer.</param>
    public void ConvertFromBytes(byte[] buffer)
    {
        age = buffer[0];
        sex = BitConverter.ToBoolean(buffer, 1);
        height = BitConverter.ToInt16(buffer, 2);
        weight = BitConverter.ToSingle(buffer, 4);
    }

    public override string ToString()
    {
        System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder("");
        stringBuilder.Append("age : " + age + "\n");
        stringBuilder.Append("sex : " + sex + "\n");
        stringBuilder.Append("height : " + height + "\n");
        stringBuilder.Append("weight : " + weight + "\n");

        return stringBuilder.ToString();
    }
}

相关文章

网友评论

      本文标题:字节流

      本文链接:https://www.haomeiwen.com/subject/npmibqtx.html