自己怎么实现Integer.toHexString(int i)函数

beibei58 2011-10-10 11:31:18
今天面试的时候遇到一个这样的问题!有点不解!新手!
就是自己怎么实现Integer.toHexString(int i)函数
...全文
297 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
打油的程序员 2011-10-11
  • 打赏
  • 举报
回复
一楼的改为这样 就可以转换负数了:


public class Test {
public static void main(String[] args) {
System.out.println(toHexString(-100));
}
public static String toHexString(int input) {
boolean b = false;//是正否为负数
if (input < 0) {
b = true;
input = -input;
}
String output = "";
int base = 16;
int c = 0;
int lowbit = 0;
base >>= 1;
do {
lowbit = input & 1;
input = (input >> 1) & 0xffffffff;
c = ((input % base) << 1) + lowbit;
if (c < 10)
c += '0';
else
c += 'A';
output += (char) c;
} while ((input /= base) != 0);

StringBuffer sb = new StringBuffer(output);

output = sb.reverse().toString();
if (b)
output = "-" + output;
return output;
}
}

打油的程序员 2011-10-11
  • 打赏
  • 举报
回复

public class Test{
public static void main(String[] args) {
System.out.println(toHexString(-100));
}
public static String toHexString(Integer i){//i>0
boolean b = false;//是正否为负数
if(i==0)return "0";
else if(i<0) {
b = true;//是负数
i=-i;
}
char[] hex = "0123456789ABCDEF".toCharArray();
String result = "" ;
while(i!=0){
result=hex[i%16]+result;
i/=16;
}
if(b) result="-"+result;
return result;
}
}

打油的程序员 2011-10-11
  • 打赏
  • 举报
回复

public class Test{
public static void main(String[] args) {
System.out.println(convert(1234));
}
public static String convert(Integer i){//i>0
char[] upperCharacter = "0123456789ABCDEF".toCharArray();
String result = "" ;
while(i!=0){
result=upperCharacter[i%16]+result;
i/=16;
}
return result;
}
}



刚才回复了一个类似的贴:http://topic.csdn.net/u/20111010/23/08e756ba-392a-4d4d-b251-1c0dac20a0cb.html?21147
我只把它改了几个数字
柯本 2011-10-10
  • 打赏
  • 举报
回复
由C改过来的,参考下:

public static String toHexString(int input)
{
String output="";
int base=16;
int c=0;
int lowbit=0;

base >>= 1;
do {
lowbit = input & 1;
input = (input >> 1) & 0xffffffff;
c = ((input % base) << 1) + lowbit;
if(c < 10)
c += '0';
else c +='A';
output+=(char)c;
} while((input/=base)!=0);

StringBuffer sb=new StringBuffer(output);

output= sb.reverse().toString();

return output;
}

51,408

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧