2016年8月4日木曜日

unity バイト配列の連結と変換サンプル

unityでバイト配列操作のメモ。
//バイト配列から値型へ変換
public static float GetMyNo(this byte[] ba)
{
float x;
x = BitConverter.ToSingle (ba, 2);
return x;
}
//バイトデータの比較
switch (test[0]) {
case (byte)'P':
Debug.Log ("P");
test = BitConverter.GetBytes ('N');
break;
case (byte)'I':
Debug.Log ("I");
test = BitConverter.GetBytes ('S');
break;
case (byte)'T':
Debug.Log ("T");
test = BitConverter.GetBytes ('P');
break;
case (byte)'S':
Debug.Log ("S");
test = BitConverter.GetBytes ('T');
break;
case (byte)'N'://ニックネーム
Debug.Log ("N");
test = BitConverter.GetBytes ('I');
break;
//各種値を一つのバイト配列へ変換
public static byte[] GetJikiByte(this Transform tr,int myNo, int jyo,bool muki)
{
byte[] ba;
ba = RenkatuByte (
BitConverter.GetBytes ('P'),
BitConverter.GetBytes (myNo),
BitConverter.GetBytes (tr.position.x),
BitConverter.GetBytes (tr.position.y),
BitConverter.GetBytes (jyo),
BitConverter.GetBytes (muki)
);
return ba;

}

//複数のバイト配列を一つのバイト配列へ連結
public static byte[] RenkatuByte(byte[] iti, byte[] nii, byte[] sann,byte[] yon,byte[] gou)
{
byte[] ret = new byte[iti.Length + nii.Length + sann.Length+yon.Length+gou.Length];
Buffer.BlockCopy(iti, 0, ret, 0, iti.Length);
Buffer.BlockCopy(nii, 0, ret, iti.Length, nii.Length);
Buffer.BlockCopy(sann, 0, ret, iti.Length + nii.Length,sann.Length);
Buffer.BlockCopy(yon, 0, ret, iti.Length + nii.Length+sann.Length,yon.Length);
Buffer.BlockCopy(gou, 0, ret, iti.Length + nii.Length+sann.Length+yon.Length,gou.Length);
return ret;
}
//6つの場合
public static byte[] RenkatuByte(byte[] iti, byte[] nii, byte[] sann,byte[] yon,byte[] gou,byte[] roku)
{
byte[] ret = new byte[iti.Length + nii.Length + sann.Length+yon.Length+gou.Length+roku.Length];
Buffer.BlockCopy(iti, 0, ret, 0, iti.Length);
Buffer.BlockCopy(nii, 0, ret, iti.Length, nii.Length);
Buffer.BlockCopy(sann, 0, ret, iti.Length + nii.Length,sann.Length);
Buffer.BlockCopy(yon, 0, ret, iti.Length + nii.Length+sann.Length,yon.Length);
Buffer.BlockCopy(gou, 0, ret, iti.Length + nii.Length+sann.Length+yon.Length,gou.Length);
Buffer.BlockCopy(roku, 0, ret, iti.Length + nii.Length+sann.Length+yon.Length+gou.Length,roku.Length);
return ret;
}

0 件のコメント:

コメントを投稿