public static class HalfByteArray
{
public static byte HalfByteAyGet(byte[] bAy, int idx)
{
int bIndex = idx / 2;
if (idx % 2 == 0)
{
return (byte)(bAy[bIndex] >> 4);
}
else
{
return (byte)(bAy[bIndex] & 0b0000_1111);
}
}
public static byte[] Byte2Half(byte[] og)
{
byte[] bAry = new byte[og.Length / 2];
for (int i = 0; i < og.Length; i += 2)
{
byte HLv0 = og[i];
byte HLv1 = og[i + 1];
byte b = (byte)((HLv0 << 4) + HLv1);
bAry[i / 2] = b;
}
return bAry;
}
public static void TestCase()
{
byte[] og = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] halfB = Byte2Half(og);
for (int i = 0; i < og.Length; i++)
{
byte back = HalfByteAyGet(halfB, i);
UnityEngine.Assertions.Assert.AreEqual(back, og[i]);
}
}
}
搜尋此網誌
2022年12月13日 星期二
C# Byte To 4 Bit 用4bit儲存資料 可以節省一半空間
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言