字节流

2019-04-02  本文已影响0人  MYves

1.基本数据类型

2. 类转字节流

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();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读