z****n 发帖数: 28 | 1 不能用Java library 的 Integer.toBinaryString(int i) , 自己写算法。大家写写看.
public static String convertToBinary(int i) {
} |
d**e 发帖数: 6098 | 2 好像很繁琐,只处理 n>= 0。谁能提供一个简易版?怎么处理负数的情况?
char * intToBinStr(int n)
{
char * binStr = 0;
int length = 0;
int remainder = 0;
int factor = 1;
int result = 0;
if(n == 0)
{
binStr = new char('0');
}
else{
while (n >= 1)
{
remainder = n % 2;
result += remainder * factor;
n = n / 2;
factor *= 10;
length++;
}
binStr = new char[length];
while(result >= 1)
{
binStr[--length] = '0' + (result % 10);
【在 z****n 的大作中提到】 : 不能用Java library 的 Integer.toBinaryString(int i) , 自己写算法。大家写写看. : public static String convertToBinary(int i) { : }
|
y*********e 发帖数: 518 | 3 上完整代码:
public String intToBits(int value) {
long i = value;
if (i < 0)
i = Integer.MAX_VALUE - (-i) + 1;
// i is unsigned then
char[] buff = new char[32];
for (int j = 31; j >= 0; j--) {
boolean bit = (i & 1 == 1);
buff[j] = '0' + (int)bit;
i = i >> 1;
}
return new String(buff);
} |
I**A 发帖数: 2345 | 4 try try this one
>>> handles the negative numbers
public static String convertDecimal2Binary(int x){
///give it enough space
byte[] bchar = new byte[32];
int bit=31;
while(x!=0){
bchar[bit] = (byte)(x%2); //(byte)(x%7)
bit--; x >>>=1; //x = x/7
}
//compose the result;
StringBuilder result = new StringBuilder();
for(int i=bit+1; i<=31; i++)
result.append(bchar[i]);
【在 d**e 的大作中提到】 : 好像很繁琐,只处理 n>= 0。谁能提供一个简易版?怎么处理负数的情况? : char * intToBinStr(int n) : { : char * binStr = 0; : int length = 0; : int remainder = 0; : int factor = 1; : int result = 0; : if(n == 0) : {
|
x*****p 发帖数: 1707 | 5 You do not have to worry about the negative integers because its binary
representation is to use the complementary code.
The code is as follows.
public static String convertToBinary(int i) {
StringBuffer sb = new StringBuffer();
int n = i;
sb.append("" + (n%2));
n>>1;
while (n>0) {
sb.append("" + (n%2));
n>>1;
}
sb.reverse();
return sb.toString();
} |
x******3 发帖数: 245 | 6 this is cool, very succinct code
【在 x*****p 的大作中提到】 : You do not have to worry about the negative integers because its binary : representation is to use the complementary code. : The code is as follows. : public static String convertToBinary(int i) { : StringBuffer sb = new StringBuffer(); : int n = i; : sb.append("" + (n%2)); : n>>1; : while (n>0) { : sb.append("" + (n%2));
|