当前位置:编程学习 > C#/ASP.NET >>

C#中如何把二进制字符串转化为二进制

比如把字符串“1001101”转化为二进制数1001101返回 --------------------编程问答-------------------- string s = "1001101";
byte b = Convert.ToByte(s, 2); --------------------编程问答--------------------
using System;

public class ByteConversion
{
   public static void Main()
   {
      string byteString = null;
      CallTryParse(byteString);

      byteString = String.Empty;
      CallTryParse(byteString);

      byteString = "1024";
      CallTryParse(byteString);

      byteString = "100.1";
      CallTryParse(byteString);

      byteString = "100";
      CallTryParse(byteString);

      byteString = "+100";
      CallTryParse(byteString);

      byteString = "-100";
      CallTryParse(byteString);

      byteString = "000000000000000100";
      CallTryParse(byteString);

      byteString = "00,100";
      CallTryParse(byteString);

      byteString = "   20   ";
      CallTryParse(byteString);

      byteString = "FF";
      CallTryParse(byteString);

      byteString = "0x1F";
      CallTryParse(byteString);
   }

   private static void CallTryParse(string stringToConvert)
   {  
      byte byteValue; 
      bool result = Byte.TryParse(stringToConvert, out byteValue);
      if (result)
      {
         Console.WriteLine("Converted '{0}' to {1}", 
                        stringToConvert, byteValue);
      }
      else
      {
         if (stringToConvert == null) stringToConvert = "";
         Console.WriteLine("Attempted conversion of '{0}' failed.", 
                           stringToConvert.ToString());
      }
   }    
}
// The example displays the following output to the console:
//       Attempted conversion of '' failed.
//       Attempted conversion of '' failed.
//       Attempted conversion of '1024' failed.
//       Attempted conversion of '100.1' failed.
//       Converted '100' to 100
//       Converted '+100' to 100
//       Attempted conversion of '-100' failed.
//       Converted '000000000000000100' to 100
//       Attempted conversion of '00,100' failed.
//       Converted '   20   ' to 20
//       Attempted conversion of 'FF' failed.
//       Attempted conversion of '0x1F' failed.
--------------------编程问答-------------------- ls两位方法都很好。

但是即使lz不懂.NET框架库,也应该能自行解决。

二进制的计算方法是
每一位 * 2的(位 - 1)次方,然后求和。
比如"1001101"
= 1 x 64 + 0 x 32 + 0 x 16 + 1 x 8 + 1 x 4 + 0 x 2 + 1 x 1。

自己应该能写出对应的程序。

还有一种办法是从右往左移位,最后得到数字。

如果系统库你都有办法自己实现,或者对原理都很清楚,学习起来就很轻松。 --------------------编程问答-------------------- 自右往左移位的确可以写出来,但太麻烦了,我想直接得到,因为本来那个字符串就是二进制字符串的。
那个wuyazhe,用你的返回好像是是十进制的,我想要二进制的
--------------------编程问答--------------------
引用 4 楼 z421113748 的回复:
自右往左移位的确可以写出来,但太麻烦了,我想直接得到,因为本来那个字符串就是二进制字符串的。
那个wuyazhe,用你的返回好像是是十进制的,我想要二进制的


计算机中数据都是2进制的,8进制,10进制,16进制只是人们用来描述这个2进制序列的方式.建议你重新温习以下这块的入门基础.4#这个回复问的很业余.
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,