-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathInt.java
More file actions
45 lines (40 loc) · 978 Bytes
/
Int.java
File metadata and controls
45 lines (40 loc) · 978 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package string;
/**
* 模仿整数
*/
public class Int {
public static void main(String[] args) {
int n = 254;
System.out.println(Int.toBinaryString(n));
System.out.println(Int.toHexString(n));
System.out.println(Int.toString(n, 8));
}
// 转换为二进制
public static String toBinaryString(int n) {
String str = "";
// 一个int占32位,右移一位,高位以0填充
for (int i = 0x80000000; i != 0; i >>>= 1)
str += (n & i) == 0 ? '0' : '1';
return str;// 返回字符串
}
// 转换为十六进制
public static String toHexString(int n) {
String str = "";
while (n > 0) {
int k = n % 16;// 除16取余法,余数存入str字符串
str = (char) (k <= 9 ? k + '0' : k + 'A' - 10) + str;// 将0-9,10-15转换成'0'-'9','A'-'F'
n /= 16;
}
return str;
}
// 转换为任意进制
public static String toString(int n, int radix) {
String str = "";
while (n > 0) {
int k = n % radix;
str += (char) (k <= 9 ? k + '0' : k - 10 + 'A');
n /= radix;
}
return str;
}
}