pri*_*kar 0 c# bit-manipulation
我有一个字符串形式的二进制数
string input = "10110101101";
Run Code Online (Sandbox Code Playgroud)
现在我需要翻转(0 to 1和1 to 0)它的前3位.
结果输出为010 10101101
如何在C#中这样做?
这有效:
string input = "10110101101";
string output =
new string(
input
.Take(3)
.Select(c => c == '0' ? '1' : '0')
.Concat(input.Skip(3))
.ToArray());
Run Code Online (Sandbox Code Playgroud)
它给出了结果:
01010101101
Run Code Online (Sandbox Code Playgroud)
另一种方法是这样做:
string input = "10110101101";
string flips = "11100000000";
int value = Convert.ToInt32(input, 2) ^ Convert.ToInt32(flips, 2);
string output = Convert.ToString(value, 2).PadLeft(input.Length, '0');
Run Code Online (Sandbox Code Playgroud)