![](/img/trans.png)
[英]Declaring a field as a bit (as a single bit, as opposed to a byte multiple) in C#
[英]how to check single bit in byte using C#
我想使用 C# 檢查接收到的串行通信字節中的單個位是高還是低
我試圖寫這樣的東西:
if(BoxSerialPort.ReadByte() & 0x01)
或者
if(Convert.ToByte(BoxSerialPort.ReadByte()) & 0x01)
編譯器發送此錯誤:
錯誤 CS0029 無法將類型“int”隱式轉換為“bool”
我怎樣才能解決這個問題?
使用&
運算符
if ((BoxSerialPort.ReadByte() & 0x01) != 0)
...
&
- 運算符檢查兩個 integer 值的每一位並返回一個新的結果值。
假設您的BoxSerialPort
是43
,即二進制0010 1011
。
0x01
或簡單的1
是二進制的0000 0001
。
&
比較每個位,如果相應位在兩個操作數中都設置了,則返回1
,否則返回0
。
0010 1011
0000 0001
=
0000 0001
(正常整數為1
)
您的 if 語句現在檢查if (1 != 0)
這顯然是正確的。 0x01
位在您的變量中設置。 &
運算符通常可以很好地確定是否在 integer 值中設置了某個位。
我會使用compareTo
using System;
//byte compare
byte num1high = 0x01;
byte num2low = 0x00;
if (num1high.CompareTo(num2low) !=0)
Console.WriteLine("not low");
if (num1high.CompareTo(num2low) == 0)
Console.WriteLine("yes is low");
Console.WriteLine(num1high.CompareTo(num2low));
Console.WriteLine(num1high.CompareTo(num1high));
Console.WriteLine(num2low.CompareTo(num1high));
output:
not low
1
0
-1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.