- ( 50% , Long.toString(n, 2) 150-400% , BigInteger.toString(2)), , , :
static String toBinary (long n) {
int neg = n < 0 ? 1 : 0;
if(n < 0) n = -n;
int pos = 0;
boolean[] a = new boolean[64];
do {
a[pos++] = n % 2 == 1;
} while ((n >>>= 1) != 0);
char[] c = new char[pos + neg];
if(neg > 0) c[0] = '-';
for (int i = 0; i < pos; i++) {
c[pos - i - 1 + neg] = a[i] ? '1' : '0';
}
return new String(c);
}
If you want the actual binary representation of Two Compliment from long(with leading 1s or 0s):
static String toBinaryTC (long n) {
char[] c = new char[64];
for(int i = 63; i >= 0; i--, n >>>= 1) {
c[i] = n % 2 != 0 ? '1' : '0';
}
return new String(c);
}
source
share