上完整代码: 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); }
k*e
9 楼
开卡bonus?那是不是拿到就可以关了,可为什么有人还交年费留着呢
【在 b**********t 的大作中提到】 : bonus
I*A
10 楼
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) : {
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*****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));