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

方法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;

}



 

转载于:https://www.cnblogs.com/lxy1998/p/6798550.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值