简体   繁体   English

你能读/写一个字节/整数/的特定位吗?

[英]Can you read/write a specific bit from a byte/int/

Coming from PLC I'm used to being able to write an individual bit.来自 PLC 我习惯于能够写一个单独的位。 if I want to write to the third bit of a byte I do the following:如果我想写入一个字节的第三位,我会执行以下操作:

byte Var1;
Var1.X2 := true;

Is there a similar way in C# to easily write to a certain bit of a byte/int?在 C# 中是否有类似的方法可以轻松写入字节/整数的某个位?

For now, I'm using the sum to get a similar result (bit1 -> +1, bit3 -> +4, ...), but being able to read/write to a specific byte would be easier.现在,我使用总和来获得类似的结果(位 1 -> +1,位 3 -> +4,...),但能够读/写特定字节会更容易。

You can use some bit arithmetic's via bitwise and shift operators :您可以通过按位和移位运算符使用一些位算术:

byte b = 8;
string binary = Convert.ToString(b, 2);
Console.WriteLine(b);
b|= 1 << 1;
Console.WriteLine(Convert.ToString(b, 2));

Or using binary literals :或者使用二进制文字

byte b = 8;
string binary = Convert.ToString(b, 2); 
Console.WriteLine(binary); // 1000
b |= 0b_0010;
Console.WriteLine(Convert.ToString(b, 2)); // 1010
b &= 0b_1101;
Console.WriteLine(Convert.ToString(b, 2)); // 1000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM