您的位置:首页 > 其它

10进制与2进制,8进制,16进制的相互转换

2013-10-20 13:31 701 查看
理解了原理不管什么进制的都可以类似的转换,只是我在转换时最开始没注意到char 类型的 0 和1 其实对应的int类型的是48 和49

这个明白了一切转换很容易

10进制与2进制的相互转换

public static void main(String[] args) {
int count = 2174;
//to 2进制
String str = "";
while(true){
str = count%2 + str;
count = count/2;
if(count<2){
str = count%2 + str;
break;
}
}
System.out.println(str);

String str1 = "100001111110";
int count1 = 0;

for(int i=str1.length()-1;i>=0;i--){
int temp = 1;
for(int j =0;j<str1.length()-i-1;j++){
temp = temp*2;
}
//System.out.println(temp);
if(str1.charAt(i) == '0'){
count1 = count1+0;
}else if(str1.charAt(i) == '1'){
count1 = count1+temp;
}
}
System.out.println(count1);

System.out.println((int)'0');
}


10进制与8进制的相互转换

public static void main(String[] args) {
int count = 125350566;
String str = "";
// to 8进制
while (true) {
str = count % 8 + str;
count = count / 8;
if (count < 8) {
str = count % 8 + str;
break;
}
}
System.out.println(str);

String count8 = "736131246";
int count10 = 0;

for (int i = count8.length() - 1; i >= 0; i--) {
int temp = 1;
for (int j = 0; j < count8.length() - i - 1; j++) {
temp = temp * 8;
}
count10 = count10 + temp * (count8.charAt(i) - 48);
}
System.out.println(count10);
}


10进制与16进制的相互转换

public static void main(String[] args) {

int count = 32311802;
String str = "";
char[] index = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
'B', 'C', 'D', 'E', 'F' };
while (true) {
str = index[count % 16] + str;
count = count / 16;
if (count < 16) {
if (count != 0)
str = index[count % 16] + str;
break;
}
}
System.out.println(str);

String str16 = "1ED09FA";
int temp = 1;
int count10 = 0;
for (int i = str16.length() - 1; i >= 0; i--) {
for (int j = 0; j < index.length; j++) {
if (str16.charAt(i) == index[j]) {
temp = j;
}
}
int temp1 = 1;
for (int j = 0; j < str16.length() - i - 1; j++) {
temp1 = temp1 * 16;
}
count10 += temp * temp1;
}
System.out.println(count10);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息