在C#中我们需要写二进制的常量,或者把二进制的字符串转成int类型。以下是示例代码:

声明一个二进制常量有以下两种写法:

int n1 = 0b0100001;
int n2 = 0b0010_0001;

那么把二进制的字符串转成int类型呢?
注意以下写法是错误的。

string str1 = "0b00010000";
int n = Convert.ToInt32(str1, 2);

string str2 = "0001_0000";
int n2 = Convert.ToInt32(str2, 2);

正确的写法如下:
 

string str = "00010000";
int n = Convert.ToInt32(str, 2);

 

要点说明

  • 二进制字面量用 0b 前缀:int n = 0b0100_0001;,可用下划线分隔提高可读性。
  • Convert.ToInt32(str, 2) 只接受纯 01 字符串,不能带 0b 前缀,也不能带下划线。
  • 因此 "0b00010000" 与 "0001_0000" 都会抛异常,必须先去掉前缀与分隔符。
  • 位数超出目标类型范围时会抛 OverflowException,注意类型容量。