码迷,mamicode.com
首页 > 其他好文 > 详细

待解:用二进制形式显示任何整数的二进制值

时间:2014-12-19 00:34:17      阅读:290      评论:0      收藏:0      [点我收藏+]

标签:style   blog   ar   io   color   os   sp   for   java   

 1 package com.java7.showbitsdemo;
 2 /*
 3  * Try This 5-3
 4  * A class that displays the binary representation of a value.
 5  */
 6 class ShowBits {
 7     int numbits;
 8     
 9     ShowBits(int n) {
10         numbits = n;
11     }
12     
13     void show(long val) {
14         long mask = 1;
15         
16         // left-shift a 1 into the proper position
17         mask <<= numbits-1;
18         
19         int spacer = 0;
20         for(; mask != 0; mask >>>=1) {
21             if((val & mask) != 0) System.out.print("1");
22             else System.out.print("0");
23             spacer++;
24             if((spacer % 8) == 0) {
25                 System.out.print("");
26                 spacer = 0;
27             }
28         }
29         System.out.println();
30     }
31 }
32 
33 // Demonstrate ShowBits.
34 class ShowBitsDemo {
35     public static void main(String[] args) {
36         ShowBits b = new ShowBits(8);
37         ShowBits i = new ShowBits(32);
38         ShowBits li = new ShowBits(64);
39         System.out.println("123 in binary: ");
40         b.show(123);
41         
42         System.out.println("\n87987 in binary: ");
43         i.show(87987);
44         
45         System.out.println("\n237658768 in binary: ");
46         li.show(237658768);
47         
48         // you can also show low-order bits of any integer
49         System.out.println("\nLow order 8 bits of 87987 in binary: ");
50         b.show(87987);
51     }
52 }

执行结果:

123 in binary: 

01111011

 

87987 in binary: 

00000000000000010101011110110011

 

237658768 in binary: 

0000000000000000000000000000000000001110001010100110001010010000

 

Low order 8 bits of 87987 in binary: 

10110011

待解:用二进制形式显示任何整数的二进制值

标签:style   blog   ar   io   color   os   sp   for   java   

原文地址:http://www.cnblogs.com/fatoland/p/4172828.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!