1. 程式人生 > >獨立項目-MemoryStream-內存數據讀寫-01

獨立項目-MemoryStream-內存數據讀寫-01

作者 dbo turn private void iou exce null 但是

學習內容:

  1.內存讀寫原理,字節的轉換。

  2.編寫自己的內存讀寫類,這個類是項目中比較核心的類。

    註:電腦中最基本的單位是“位”(bit),但是“位”(bit)這個單位太小,所以字節(Byte)是電腦存儲容量的基本計量單位。Byte可簡寫成位B,一個字節由8個二進制位組成,其最小值位0,最大值為11111111,一個存儲單元能存儲一個字節的內容。

  一、int轉換為byte 與 byte轉換為int示例:

#region 模塊信息
// **********************************************************************
// Copyright (C) 2018 The company name // // 文件名(File Name): Test_MMOMemory.cs // 作者(Author): Dean1874 // 創建時間(CreateTime): 2018-04-04 18:19:14 // 修改者列表(modifier): // 模塊描述(Module description): // // ********************************************************************** #endregion using
System; using UnityEngine; public class Test_MMOMemory : MonoBehaviour { private void Start() { IntToByte(); ByteToInt(); } /// <summary> /// 把int轉換成byte數據 /// </summary> private void IntToByte() {//int 4個字節(4個byte) int a = 10; //把int轉換成byte數據
byte[] array1 = BitConverter.GetBytes(a); //提示:循環盡量用for,少用foreach for (int i = 0; i < array1.Length; ++i) { Debug.Log(string.Format("array1{0} = {1}", i, array1[i])); } //int 4個字節(4個byte) int b = 98; //把int轉換成byte數據 byte[] array2 = BitConverter.GetBytes(b); //提示:循環盡量用for,少用foreach for (int i = 0; i < array2.Length; ++i) { Debug.Log(string.Format("array2{0} = {1}", i, array2[i])); } //int 4個字節(4個byte) int c = 8998; //把int轉換成byte數據 byte[] array3 = BitConverter.GetBytes(c); //提示:循環盡量用for,少用foreach for (int i = 0; i < array3.Length; ++i) { Debug.Log(string.Format("array3{0} = {1}", i, array3[i])); } } private void ByteToInt() { byte[] array = new byte[4]; array[0] = 86; array[1] = 128; array[2] = 224; array[3] = 5; int a = BitConverter.ToInt32(array, 0); Debug.Log(string.Format("a = {0}", a)); } }

  二、如何寫自己的MMO_MemoryStream腳本:

#region 模塊信息
// **********************************************************************
// Copyright (C) 2018 The company name
//
// 文件名(File Name):             MMO_MemoryStream.cs
// 作者(Author):                  Dean1874
// 創建時間(CreateTime):          2018-04-04 18:39:06
// 修改者列表(modifier):
// 模塊描述(Module description):
// 
// **********************************************************************
#endregion

using System;
using System.IO;
using System.Text;
using UnityEngine;

/// <summary>
/// 數據轉換(byte、short、int、long、float、decimal、bool、string)
/// </summary>
public class MMO_MemoryStream : MemoryStream 
{
    /// <summary>
    /// 構造函數 傳遞給基類
    /// </summary>
    /// <param name="buffer"></param>
    public MMO_MemoryStream(byte[] buffer):base(buffer)
    {
    }

    /// <summary>
    /// 構造函數
    /// </summary>
    public MMO_MemoryStream() : base()
    {

    }

    #region short相關

    /// <summary>
    /// 從流中讀取一個short數據
    /// </summary>
    /// <returns></returns>
    public short ReadShort()
    {
        byte[] array = new byte[2];
        base.Read(array, 0, 2);

        return BitConverter.ToInt16(array, 0);
    }

    /// <summary>
    /// 把一個short數據寫入流
    /// </summary>
    /// <param name="_value"></param>
    public void WriteShort(short _value)
    {
        byte[] array = BitConverter.GetBytes(_value);
        base.Write(array, 0, array.Length);
    }

    #endregion

    #region ushort相關

    /// <summary>
    /// 從流中讀取一個ushort數據
    /// </summary>
    /// <returns></returns>
    public ushort ReadUShort()
    {
        byte[] array = new byte[2];
        base.Read(array, 0, 2);

        return BitConverter.ToUInt16(array, 0);
    }

    /// <summary>
    /// 把一個ushort數據寫入流
    /// </summary>
    /// <param name="_value"></param>
    public void WriteUShort(ushort _value)
    {
        byte[] array = BitConverter.GetBytes(_value);
        base.Write(array, 0, array.Length);
    }

    #endregion

    #region int相關

    /// <summary>
    /// 從流中讀取一個int數據
    /// </summary>
    /// <returns></returns>
    public int ReadInt()
    {
        byte[] array = new byte[4];
        base.Read(array, 0, 4);

        return BitConverter.ToInt32(array, 0);
    }

    /// <summary>
    /// 把一個int數據寫入流
    /// </summary>
    /// <param name="_value"></param>
    public void WriteInt(int _value)
    {
        byte[] array = BitConverter.GetBytes(_value);
        base.Write(array, 0, array.Length);
    }

    #endregion

    #region uint相關

    /// <summary>
    /// 從流中讀取一個uint數據
    /// </summary>
    /// <returns></returns>
    public uint ReadUInt()
    {
        byte[] array = new byte[4];
        base.Read(array, 0, 4);

        return BitConverter.ToUInt32(array, 0);
    }

    /// <summary>
    /// 把一個uint數據寫入流
    /// </summary>
    /// <param name="_value"></param>
    public void WriteUInt(uint _value)
    {
        byte[] array = BitConverter.GetBytes(_value);
        base.Write(array, 0, array.Length);
    }

    #endregion

    #region long相關

    /// <summary>
    /// 從流中讀取一個long數據
    /// </summary>
    /// <returns></returns>
    public long ReadLong()
    {
        byte[] array = new byte[8];
        base.Read(array, 0, 8);

        return BitConverter.ToInt64(array, 0);
    }

    /// <summary>
    /// 把一個long數據寫入流
    /// </summary>
    /// <param name="_value"></param>
    public void WriteLong(long _value)
    {
        byte[] array = BitConverter.GetBytes(_value);
        base.Write(array, 0, array.Length);
    }

    #endregion

    #region ulong相關

    /// <summary>
    /// 從流中讀取一個ulong數據
    /// </summary>
    /// <returns></returns>
    public ulong ReadULong()
    {
        byte[] array = new byte[8];
        base.Read(array, 0, 8);

        return BitConverter.ToUInt64(array, 0);
    }

    /// <summary>
    /// 把一個ulong數據寫入流
    /// </summary>
    /// <param name="_value"></param>
    public void WriteULong(ulong _value)
    {
        byte[] array = BitConverter.GetBytes(_value);
        base.Write(array, 0, array.Length);
    }

    #endregion

    #region float相關

    /// <summary>
    /// 從流中讀取一個float數據
    /// </summary>
    /// <returns></returns>
    public float ReadFloat()
    {
        byte[] array = new byte[4];
        base.Read(array, 0, 4);

        return BitConverter.ToSingle(array, 0);
    }

    /// <summary>
    /// 把一個float數據寫入流
    /// </summary>
    /// <param name="_value"></param>
    public void WriteFloat(float _value)
    {
        byte[] array = BitConverter.GetBytes(_value);
        base.Write(array, 0, array.Length);
    }

    #endregion

    #region double相關

    /// <summary>
    /// 從流中讀取一個double數據
    /// </summary>
    /// <returns></returns>
    public double ReadDouble()
    {
        byte[] array = new byte[8];
        base.Read(array, 0, 8);

        return BitConverter.ToDouble(array, 0);
    }

    /// <summary>
    /// 把一個double數據寫入流
    /// </summary>
    /// <param name="_value"></param>
    public void WriteDouble (double _value)
    {
        byte[] array = BitConverter.GetBytes(_value);
        base.Write(array, 0, array.Length);
    }

    #endregion

    #region bool相關

    /// <summary>
    /// 從流中讀取一個bool數據
    /// </summary>
    /// <returns></returns>
    public bool ReadBool()
    {
        return base.ReadByte() == 1;
    }

    /// <summary>
    /// 把一個bool數據寫入流
    /// </summary>
    /// <param name="_value"></param>
    public void WriteBool(bool _value)
    {
        base.WriteByte((byte)(_value == true ? 1 : 0));
    }

    #endregion

    #region UTF8String相關
    /// <summary>
    /// 從流中讀取一個string數據
    /// </summary>
    /// <returns></returns>
    public string ReadUTF8String()
    {
        ushort len = ReadUShort();
        byte[] array = new byte[len];
        base.Read(array, 0, len);

        return Encoding.UTF8.GetString(array);
    }

    /// <summary>
    /// 把一個string數據寫入流
    /// </summary>
    /// <param name="_value"></param>
    public void WriteUTF8String(string _value)
    {
        byte[] array = Encoding.UTF8.GetBytes(_value);

        if (array.Length > 65535)
        {
            throw new InvalidCastException("字符串超出範圍");
        }

        //先寫入字符串的長度
        WriteUShort((ushort)array.Length);

        //再將字符串寫入
        base.Write(array, 0, array.Length);
    }
    #endregion
}

  三、在 Test_MMOMemory.cs 腳本中測試 MMO_MemoryStream.cs 腳本

#region 模塊信息
// **********************************************************************
// Copyright (C) 2018 The company name
//
// 文件名(File Name):             Test_MMOMemory.cs
// 作者(Author):                  Dean1874
// 創建時間(CreateTime):          2018-04-04 18:19:14
// 修改者列表(modifier):
// 模塊描述(Module description):
// 
// **********************************************************************
#endregion

using System;
using UnityEngine;

public class Item
{
    public int ID;
    public string Name;
}

public class Test_MMOMemory : MonoBehaviour 
{
    private void Start()
    {
        Item item = new Item() { ID = 1874, Name = "Dean1993"};

        byte[] array = null;

        //using自動釋放
        using (MMO_MemoryStream ms = new MMO_MemoryStream())
        {
            //寫入流
            ms.WriteInt(item.ID);
            ms.WriteUTF8String(item.Name);

            array = ms.ToArray();
        }

        if (array != null)
        {
            for (int i = 0; i < array.Length; ++i)
            {
                Debug.Log(string.Format("{0} = {1}", i, array[i]));
            }
        }

        Item item2 = new Item();
        using (MMO_MemoryStream ms = new MMO_MemoryStream(array))
        {
            item2.ID = ms.ReadInt();
            item2.Name = ms.ReadUTF8String();
        }

        Debug.Log(string.Format("item2 ID = {0}", item2.ID));
        Debug.Log(string.Format("item2 Name = {0}", item2.Name));
    }

    /// <summary>
    /// 把int轉換成byte數據
    /// </summary>
    private void IntToByte()
    {//int 4個字節(4個byte)
        int a = 10;

        //把int轉換成byte數據
        byte[] array1 = BitConverter.GetBytes(a);

        //提示:循環盡量用for,少用foreach
        for (int i = 0; i < array1.Length; ++i)
        {
            Debug.Log(string.Format("array1{0} = {1}", i, array1[i]));
        }

        //int 4個字節(4個byte)
        int b = 98;

        //把int轉換成byte數據
        byte[] array2 = BitConverter.GetBytes(b);

        //提示:循環盡量用for,少用foreach
        for (int i = 0; i < array2.Length; ++i)
        {
            Debug.Log(string.Format("array2{0} = {1}", i, array2[i]));
        }

        //int 4個字節(4個byte)
        int c = 8998;

        //把int轉換成byte數據
        byte[] array3 = BitConverter.GetBytes(c);

        //提示:循環盡量用for,少用foreach
        for (int i = 0; i < array3.Length; ++i)
        {
            Debug.Log(string.Format("array3{0} = {1}", i, array3[i]));
        }
    }

    private void ByteToInt()
    {
        byte[] array = new byte[4];
        array[0] = 86;
        array[1] = 128;
        array[2] = 224;
        array[3] = 5;

        int a = BitConverter.ToInt32(array, 0);
        Debug.Log(string.Format("a = {0}", a));
    }
}

獨立項目-MemoryStream-內存數據讀寫-01