十进制数字转成十六进制表示的算法
public String intToComplement(int num) {
StringBuilder sb = new StringBuilder();
if (num >= 0) {
for (int i = 0; i < 8; i++) {
int temp = num % 16;
if (temp >= 10) {
sb.append((char) (temp - 10 + 'a'));
}
else {
sb.append(temp);
}
num /= 16;
}
}
else {
int[] a = new int[32];
a[0] = 1;
num = -num;
//求出原码
for (int i = 0; i < 31; i++) {
int temp = num % 2;
a[31 - i] = temp;
num /= 2;
}
//求反码
for (int i = 0; i < 31; i++) {
if (a[31 - i] == 1) {
a[31 - i] = 0;
}
else {
a[31 - i] = 1;
}
}
//求补码
int carry = 1;
for (int i = 0; i < 31; i++) {
int x = (carry + a[31 - i]) % 2;
carry = (carry + a[31 - i]) / 2;
a[31 - i] = x;
}
for (int i = 0; i < 8; i++) {
int y = 0;
for (int j = 0; j < 4; j++) {
y += a[31 - 4 * i - j] * (int) Math.pow(2, j);
}
if (y >= 10) {
sb.append((char)(y - 10 + 'a'));
}
else {
sb.append(y);
}
}
}
sb.append("x0");
sb.reverse();
return sb.toString();
}
附带一个二进制、十进制、十六进制的表格
16进制 | 10进制 | 2进制 |
---|---|---|
0 | 0 | 0000 |
1 | 1 | 0001 |
2 | 2 | 0010 |
3 | 3 | 0011 |
4 | 4 | 0100 |
5 | 5 | 0101 |
6 | 6 | 0110 |
7 | 7 | 0111 |
8 | 8 | 1000 |
9 | 9 | 1001 |
a | 10 | 1010 |
b | 11 | 1011 |
c | 12 | 1100 |
d | 13 | 1101 |
e | 14 | 1110 |
f | 15 | 1111 |