日期:2014-05-20  浏览次数:20723 次

java中如何将十进制转换为十六进制(算法)
用java语言写一个方法 "String   hexToStr(int   input) ",所得到的结果如下所示:
如:         输入/输出
              input=1           output=1
              input=10         output=a
              input=100       output=64
              input=333       output=14d
要求:不能直接调用Integer.toHexString(xxx)

本题主要就是要写出   Integer.toHexString(xxx)的算法.

------解决方案--------------------
用C写吧,java我刚学
#include <stdio.h>
char* toString(int b[],int k)
{
char a[k];
char s[]= "0123456789ABCDEF ";
int i;
for(i=0;i <k;i++)
a[i]=s[b[k-i-1]];

return a;
}
char* changeIntToHex(int n){
int b[1000];
int k=0;
while(n!=0){
b[k]=n%16;
n/=16;
k++;
}
return toString(b,k);
}

int main(){
int n;
scanf( "%d ",&n);
printf( "%s ",changeIntToHex(n));
return 0;
}

------解决方案--------------------
public String HexToStr(int i) {
String s = "0123456789abcdef ";
StringBuffer sb = new StringBuffer();
for (int j = 0; i > = 16; j++) {
int a = i % 16;
i /= 16;
sb.append(s.charAt(a));
}
sb.append(s.charAt(i));
return sb.reverse().toString();
}
------解决方案--------------------
private static final char[] hexes = { '0 ', '1 ', '2 ', '3 ', '4 ', '5 ', '6 ', '7 ', '8 ', '9 ', 'a ', 'b ', 'c ', 'd ', 'e ', 'f '};
public static String hex2Str(int iVal) {
StringBuffer sb = new StringBuffer(8);
boolean started = false;
for (int i = 24; i > = 0; i -= 8) {
byte b = (byte)(iVal > > i);
int val = b > > 4;
if (val > 0 || started) {
started = true;
sb.append(hexes[b > > 4]);
}
val = b & 15;
if (val > 0 || started) {
started = true;
sb.append(hexes[b & 15]);
}
}
return sb.toString();
}