嗚嗚喔學習筆記: Byte & Bool[] 互相轉換

搜尋此網誌

2020年10月22日 星期四

Byte & Bool[] 互相轉換

因為 1 byte = 8 bit 所以可以用來轉換。
8 個 bool 相當於 4byte*4 = 16 byte 的大小 ( 1 bool => 4 byte )
如果存在 1 個 byte 中 就可以節省 15 byte , 還蠻省的~

        public static void Byte2Flags(bool[] flags, byte range)
{
if (flags == null || flags.Length < 8)
{
return;
}
for (int i = 0; i < 8; i++)
flags[i] = (range & (1 << i)) > 0;
}
public static byte Flags2Byte(bool[] flags)
{
byte range = 0;
if (flags == null || flags.Length < 8)
{
range = 0;
}
for (int i = 0; i < 8; i++)
{
if (flags[i])
{
range |= (byte)(1 << i);
}
}
return range;
}

沒有留言:

張貼留言