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

十进制转换为二进制的方法

时间:2017-05-02 22:17:10      阅读:252      评论:0      收藏:0      [点我收藏+]

标签:set   signed   while   offset   const   二进制   参数   else   shift   

方法1

java.lang包里integer类下有一个方法 toBinaryString

public static String toBinaryString(int i)
以二进制(基数 2)无符号整数形式返回一个整数参数的字符串表示形式。

如果参数为负,该无符号整数值为参数加上 232;否则等于该参数。将该值转换为二进制(基数 2)形式的无前导 0 的 ASCII 数字字符串。如果无符号数的大小为零,则用一个零字符 ‘0‘ (’\u0030’) 表示它;否则,无符号数大小的表示形式中的第一个字符将不是零字符。字符 ‘0‘ (‘\u0030‘) 和 ‘1‘ (‘\u0031‘) 被用作二进制数字。  

 例如

String a = Integer.toBinaryString(7);
System.out.print(a);
输出
111
源代码

public static String toBinaryString(int i) {
return toUnsignedString0(i, 1);
}


/**
* Convert the integer to an unsigned number.
*/
private static String toUnsignedString0(int val, int shift) {
// assert shift > 0 && shift <=5 : "Illegal shift value";
int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);//Integer.SIZE=32,Integer.numberOfLeadingZeros是求补码前面的0的个数
int chars = Math.max(((mag + (shift - 1)) / shift), 1);
char[] buf = new char[chars];


formatUnsignedInt(val, shift, buf, 0, chars);


// Use special constructor which takes over "buf".
return new String(buf, true);
}


/**
* Format a long (treated as unsigned) into a character buffer.
* @param val the unsigned int to format
* @param shift the log2 of the base to format in (4 for hex, 3 for octal, 1 for binary)
* @param buf the character buffer to write to
* @param offset the offset in the destination buffer to start at
* @param len the number of characters to write
* @return the lowest character location used
*/
static int formatUnsignedInt(int val, int shift, char[] buf, int offset, int len) {
int charPos = len;
int radix = 1 << shift;
int mask = radix - 1;
do {
buf[offset + --charPos] = Integer.digits[val & mask];//前面有一个digits数组
val >>>= shift;
} while (val != 0 && charPos > 0);


return charPos;
}

方法2

要求转换为n位的二进制数

int m =7//要转换的数

int[] a = new int[n];
for (int i = n-1; i >= 0; i--) {
if ((m & (1 << i)) != 0) //按位与
a[i]=1;
else
a[i] = 0;

}



 

十进制转换为二进制的方法

标签:set   signed   while   offset   const   二进制   参数   else   shift   

原文地址:http://www.cnblogs.com/lxy1998/p/6798550.html

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