似乎是基本的,但我不知道如何從字節中獲取每個位。感謝您的幫助如何從字節返回位
Q
如何從字節返回位
2
A
回答
2
由於RyuuGan已經發布,你應該去與BitArrary。您只需通過調用帶有所需元素的構造函數將數據放入其中即可。
byte[] myBytes = new byte[5] { 1, 2, 3, 4, 5 };
BitArray bitArray = new BitArray(myBytes);
之後,該實例有一些有趣的屬性可以輕鬆訪問每一位。首先,你可以只調用索引操作者獲取或設置每個位的狀態:
bool bit = bitArray[4];
bitArray[2] = true;
您也可以通過只使用一個foreach循環枚舉所有位(或任何你喜歡的LINQ的東西)
foreach (var bit in bitArray.Cast<bool>())
{
Console.Write(bit + " ");
}
要想從比特到某些特定類型(如int),背面是有點麻煩,但很容易使用這個擴展方法:
public static class Extensions
{
public static IList<TResult> GetBitsAs<TResult>(this BitArray bits) where TResult : struct
{
return GetBitsAs<TResult>(bits, 0);
}
/// <summary>
/// Gets the bits from an BitArray as an IList combined to the given type.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="bits">An array of bit values, which are represented as Booleans.</param>
/// <param name="index">The zero-based index in array at which copying begins.</param>
/// <returns>An read-only IList containing all bits combined to the given type.</returns>
public static IList<TResult> GetBitsAs<TResult>(this BitArray bits, int index) where TResult : struct
{
var instance = default(TResult);
var type = instance.GetType();
int sizeOfType = Marshal.SizeOf(type);
int arraySize = (int)Math.Ceiling(((bits.Count - index)/8.0)/sizeOfType);
var array = new TResult[arraySize];
bits.CopyTo(array, index);
return array;
}
}
有了這個地方,你可以乾脆退出的它用這一行代碼:
IList<int> result = bitArray.GetBitsAs<int>();
1
使用
Convert.ToString (value, 2)
1
使用移位。
例如,位3:b =(值>> 3)& 1;
最終和麪具位1 如果你想布爾,只是比較(==)以上,其值爲1
3
的位由右至左「編號爲」 0〜7。因此,要獲得第5位,你會使用byte & (1<<5)
我敢肯定有解釋的更清楚的方式該> _>
編輯:這將在IF
聲明中工作,但如果你只想要1 0具體來說,使用winwaed的解決方案。
2
嘗試使用BitArray。
byte[] myBytes = new byte[5] { 1, 2, 3, 4, 5 };
BitArray myBA3 = new BitArray(myBytes);
相關問題
- 1. 如何從字符串字符中返回unicode 8字節值
- 2. Android:位圖到字節數組和返回:SkImageDecoder :: Factory返回null
- 3. C#,位和字節 - 如何從字節中檢索位值?
- 4. 如何從32位/ 24位從字節到16位轉換爲字節
- 5. 如何返回線程安全字節[]?
- 6. 如何從節點mysql返回結果
- 7. 如何從QTreeView返回節點名稱
- 8. 從PropertyInfo獲取字節[]返回NULL
- 9. 從字節返回文件下載[]
- 10. 從JNI返回一個字節[]到Java
- 11. FileInputStream.available()返回字節,但ObjectInputStream.available()返回0
- 12. 如何從AsyncTask返回位圖?
- 13. 如何從ASP.NET Web服務返回原始字節?
- 14. 如何從節點-js中的UUID返回字符串
- 15. 如何從鍊金術中返回字節數組C
- 16. 如何從C++同時返回狀態和字節[]爲Java
- 17. 如何從方法返回未知大小的字節數組
- 18. 如何將字節從C返回到C#/。net?
- 19. 如何保存從WCF調用返回的字節[]?
- 20. 如何從Erlang C節點返回字符串?
- 21. 如何從C++返回一個字節數組到C#
- 22. 如何從位流中組裝字節?
- 23. 如何從字節獲取位值?
- 24. SQL如何從字符串返回特定位置?
- 25. 如何從字節字中獲取所選位的位置值
- 26. WebClient.DownloadData()返回0字節
- 27. c#SslStream.EndRead返回零字節
- 28. NSData返回0字節
- 29. 讀返回0字節
- 30. Webservice返回字節數組
位3被零引用。 IE瀏覽器。最低值位爲0.對於一個字節,最高值爲7 – winwaed 2010-11-15 03:11:55