Dựa trên @ giải pháp Paulo Ebermann tôi đã đưa ra một này:
public static String convert(long x) {
return new BigInteger(1, new byte[] { (byte) (x >> 56),
(byte) (x >> 48), (byte) (x >> 40), (byte) (x >> 32),
(byte) (x >> 24), (byte) (x >> 16), (byte) (x >> 8),
(byte) (x >> 0) }).toString();
}
Sử dụng new BigInteger(int signum, byte[] bytes);
làm BigInteger để đọc byte là số dương (unsigned) và áp dụng signum cho nó.
Dựa trên giải pháp Jester-Young @ Chris Tôi thấy điều này một:
private static DecimalFormat zero = new DecimalFormat("0000000000000000000");
public static String convert(long x) {
if (x >= 0) // this is positive
return "0" + zero.format(x);
// unsigned value + Long.MAX_VALUE + 1
x &= Long.MAX_VALUE;
long low = x % 10 + Long.MAX_VALUE % 10 + 1;
long high = x/10 + Long.MAX_VALUE/10 + low/10;
return zero.format(high) + low % 10;
}
Tuy nhiên, một cách khác để làm điều đó:
private static DecimalFormat zero19 = new DecimalFormat("0000000000000000000");
public static String convert(long x) {
if (x >= 0) {
return "0" + zero19.format(x);
} else if (x >= -8446744073709551616L) {
// if: x + 18446744073709551616 >= 10000000000000000000
// then: x + 18446744073709551616 = "1" + (x + 8446744073709551616)
return "1" + zero19.format(x + 8446744073709551616L);
} else {
// if: x + 18446744073709551616 < 10000000000000000000
// then: x + 18446744073709551616 = "09" + (x + 9446744073709551616)
// so: 9446744073709551616 == -9000000000000000000L
return "09" + (x - 9000000000000000000L);
}
}
Nguồn
2011-08-11 19:45:56
@parsifal http://en.wikipedia.org/wiki/ Twos_complement –