給定二進制字符串 "1111 1111"(或無空格 "11111111"),需要實現兩種操作:
"0000 0000"。"1111 0000"。優先使用 .NET 框架內置方法,避免手動逐字符處理。
將二進制字符串 → 整數 → 位運算 → 二進制字符串,比字符串操作高效且不易出錯。
using System;
public class BinaryFlipDemo
{
public static void Main()
{
string binaryStr = "11111111"; // 輸入可帶空格,先清理
binaryStr = binaryStr.Replace(" ", ""); // 移除空格
// 1. 字符串 → 字節 (byte 足夠 8 位)
byte value = Convert.ToByte(binaryStr, 2); // 基數 2 解析
// 2. 全位取反 (按位非 ~)
byte flippedAll = (byte)~value; // 需轉回 byte 截斷高位
Console.WriteLine($"全位取反: {ToBinaryString(flippedAll)}"); // 00000000
// 3. 低四位取反 (與 0x0F 異或 ^)
byte flippedLow4 = (byte)(value ^ 0x0F); // 0x0F = 00001111
Console.WriteLine($"低四位取反: {ToBinaryString(flippedLow4)}"); // 11110000
// 4. 通用方法:指定位數取反
Console.WriteLine($"高四位取反: {ToBinaryString(FlipBits(value, 4, 4))}"); // 00001111
Console.WriteLine($"第 2-5 位取反: {ToBinaryString(FlipBits(value, 1, 4))}"); // 11110011
}
///
/// 將字節格式化為 8 位二進制字符串 (可選帶空格)
///
static string ToBinaryString(byte b, bool withSpace = true)
{
string s = Convert.ToString(b, 2).PadLeft(8, '0');
return withSpace ? s.Insert(4, " ") : s;
}
///
/// 通用位翻轉:從 startBit (0=LSB) 開始,翻轉 count 位
///
static byte FlipBits(byte value, int startBit, int count)
{
if (startBit < 0 || count <= 0 || startBit + count > 8)
throw new ArgumentOutOfRangeException();
byte mask = (byte)(((1 << count) - 1) << startBit); // 生成掩碼
return (byte)(value ^ mask); // 異或翻轉
}
}
| 方法 | 用途 | 示例 |
|---|---|---|
Convert.ToByte(str, 2) | 二進制字符串 → 字節 | Convert.ToByte("1111", 2) = 15 |
Convert.ToString(val, 2) | 數值 → 二進制字符串 | Convert.ToString(15, 2) = "1111" |
~value | 按位取反 (所有位) | ~15 = -16 → (byte)~15 = 240 |
value ^ mask | 異或操作實現指定位翻轉 | 15 ^ 0x0F = 240 |
若超過 8 位(如 16、32、64 位),使用 ushort、uint、ulong 對應 Convert.ToUInt16/32/64,位運算邏輯完全一致。
int、short)用 ~ 會保留符號位,建議用無符號類型或顯式掩碼。Replace(" ", "") 移除空格/下劃線等分隔符。1 << 32 在 int 上未定義行為)。