这是我自己写的代码,有问题希望指出。
十进制转二进制
1 class DecToBin 2 { 3 public static void main(String[] args) 4 { 5 //System.out.println("Hello World!"); 6 long dec = -9223372036854775807l; 7 // -9223372036854775808 这个数不行,不要试,嘿嘿 8 String binStr=""; 9 long decAbs=Math.abs(dec); 10 while (decAbs>0) 11 { binStr=(decAbs&1)+binStr; 12 decAbs>>=1; 13 } 14 binStr= dec<0?"-"+binStr:dec==0?"0":binStr; 15 16 System.out.println(binStr); 17 } 18 }
十进制转八进制
1 class DecToOct 2 { 3 public static void main(String[] args) 4 { 5 //System.out.println("Hello World!"); 6 long dec=-0;//有-0 吗? 7 String octStr=""; 8 long decAbs=Math.abs(dec); 9 while (decAbs>0) 10 { octStr=(decAbs&7)+octStr;// 11 decAbs>>=3; 12 } 13 octStr= dec<0?"-"+octStr:dec==0?"0":octStr; 14 System.out.println(octStr); 15 } 16 }
十进制转十六进制
1 class DecToHex 2 { 3 public static void main(String[] args) 4 { 5 System.out.println("Hello World!"); 6 long dec=-1;//计算器的负数不会弄 -。- 7 String hexStr=""; 8 9 long decAbs=Math.abs(dec); 10 while(decAbs>0) 11 { long lastFour=decAbs&15; 12 if (lastFour>9) 13 hexStr=(char)(‘A‘+lastFour-10)+hexStr; 14 else hexStr=lastFour+hexStr; 15 decAbs>>=4; 16 } 17 18 hexStr= dec<0?"-"+hexStr:dec==0?"0":hexStr; 19 System.out.println(hexStr); 20 } 21 }
时间: 2024-12-16 19:53:34