判断一个整数的某个比特位是否为1

作者:追风剑情 发布于:2016-2-21 22:59 分类:C#

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace BigPower
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. int d = 9;
  13. Console.WriteLine(Convert.ToString(d, 2));
  14.  
  15. Console.WriteLine(TestBit(d, 0));
  16. Console.WriteLine(TestBit(d, 1));
  17. Console.WriteLine(TestBit(d, 2));
  18. Console.WriteLine(TestBit(d, 3));
  19.  
  20. Console.Read();
  21. }
  22.  
  23. // 判断整数的第i位置是否为1 (i从0开始)
  24. public static bool TestBit(int d, int i)
  25. {
  26. int b = (d >> i) & 1;
  27. return b == 1;
  28. }
  29. }
  30. }

运行效果

11111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号