将整数转换为十六进制,其中十进制1表示为FFFFFF



我一直在尝试解决以下模拟试卷问题,不幸的是,我无法合理化如何将十进制1转换为十六进制"ffffff"字符串。希望有人能给我指出正确的方向,因为即使是真正的整数。toextstring为1个十进制返回1个十六进制字符串。

问题陈述:

假设您被禁止使用printf或整数。toHexString,或者任何其他现有的库方法但是您仍然需要将十六进制的Java整数显示为1到8位数。例如,您要显示数字19(十进制)作为字符串13,1必须输出为ffffffff。

编写一个名为toHex的Java方法,以一个整数作为参数并返回它的十六进制表示的字符串形式

我的代码如下:

public class Main {
public static String toHex(int d) {
String digits = "0123456789ABCDEF";
if (d <= 0) return "0";
int base = 16; 
String hex = "";
while (d > 0) {
int digit = d % base;              // rightmost digit
hex = digits.charAt(digit) + hex;  // string concatenation
d = d / base;
}
return hex;
}

public static void main(String[] args) {
System.out.println(Integer.toHexString(-1)); // outputs: ffffff
System.out.println(Integer.toHexString(1)); // outputs: 1
System.out.println(Main.toHex(1)); // outputs: 1
}
}

我最终用如下方法解决了这个问题:

public class Main {
public static String toHex(int d) {
if(d == 0) {
return "0";
}
String codes = "0123456789abcdef";
StringBuilder builder = new StringBuilder(8);
builder.setLength(8);
for (int i = 7; i >= 0; i--) {
/**
* 19 in binary is 10011 and 15 is 01111, when using & (and) bitwise operator
* It becomes 00011, which is 3
*/
builder.setCharAt(i, codes.charAt(d & 15));
/**
*  Right arithmetic shift, for example:
*  19 in binary is 10011 after shifting to the right 4 places it becomes
*  00001
*/
d >>= 4;
}
return removeLeadingZeros(builder.toString());
}
public static String removeLeadingZeros(String str){
StringBuilder strB = new StringBuilder(str);
int index = 0;
while (strB.length() > 0 && strB.charAt(index) == '0') {
strB.deleteCharAt(index);
}
return strB.toString();
}

public static void main(String[] args) {
System.out.println(toHex(-1).equals(Integer.toHexString(-1))); // true
System.out.println(toHex(19).equals(Integer.toHexString(19))); // true
}
}

我要感谢@rzwitserloot和@trincot为我指出了正确的方向。

十六进制代码可以在eddmann找到,我添加了一些注释和删除前导零的能力。

希望这对其他遇到类似问题的人有所帮助。

关于算术移位和位运算的更多信息