[英]Encode bool array as ushort
假設我們有一個布爾值數組,一些是正確的,一些是錯誤的。 我喜歡生成一個ushort
並根據數組設置位。
ushort
包含2個字節,即16位。
因此,如果數組中的第一個布爾值為true,則需要設置ushort
的第一位,否則該位將為0。需要對ushort
每個位重復此操作。
我將如何設置一個方法數組,它以布爾數組作為輸入並返回編碼的ushort? (C#)
您可以使用BitConverter類( https://msdn.microsoft.com/zh-cn/library/bb384066.aspx )以便將字節轉換為int和二進制運算(例如在此StackOverflow問題中: How我可以將位轉換為字節嗎? )將位轉換為字節
例如:
//Bools to Bytes...
bool[] bools = ...
BitArray a = new BitArray(bools);
byte[] bytes = new byte[a.Length / 8];
a.CopyTo(bytes, 0);
//Bytes to ints
int newInt = BitConverter.ToInt32(bytes); //Change the "32" to however many bits are in your number, like 16 for a short
這僅適用於一個int,因此,如果單個位數組中有多個int,則需要拆分該數組才能使用此方法。
BitArray可能更適合您的用例: https : //msdn.microsoft.com/zh-cn/library/system.collections.bitarray(v= vs.110).aspx
bool[] myBools = new bool[5] { true, false, true, true, false };
BitArray myBA = new BitArray(myBools);
foreach (var value in myBA)
{
if((bool)value == true)
{
}
else
{
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.