java 十进制十六进制转换,Java中的十进制到十六进制转换器

I have a homework assignment where I need to do three-way conversion between decimal, binary and hexadecimal. The function I need help with is converting a decimal into a hexadecimal. I have nearly no understanding of hexadecimal, nonetheless how to convert a decimal into hex. I need a function that takes in an int dec and returns a String hex. Unfortunately I don't have any draft of this function, I'm completely lost. All I have is this.

public static String decToHex(int dec)

{

String hex = "";

return hex;

}

Also I can't use those premade functions like Integer.toHexString() or anything, I need to actually make the algorithm or I wouldn't have learned anything.

解决方案

One possible solution:

import java.lang.StringBuilder;

class Test {

private static final int sizeOfIntInHalfBytes = 8;

private static final int numberOfBitsInAHalfByte = 4;

private static final int halfByte = 0x0F;

private static final char[] hexDigits = {

'0', '1', '2', '3', '4', '5', '6', '7',

'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'

};

public static String decToHex(int dec) {

StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);

hexBuilder.setLength(sizeOfIntInHalfBytes);

for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i)

{

int j = dec & halfByte;

hexBuilder.setCharAt(i, hexDigits[j]);

dec >>= numberOfBitsInAHalfByte;

}

return hexBuilder.toString();

}

public static void main(String[] args) {

int dec = 305445566;

String hex = decToHex(dec);

System.out.println(hex);

}

}

Output:

1234BABE

Anyway, there is a library method for this:

String hex = Integer.toHexString(dec);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值