我写了两个函数,接受一个整数,将其转换成十六进制值并返回字节值。
例如
Scenario 1
十进制值-400Hexadecimal值-0x190getYLHeight()应该返回90getYHHeight()应该返回1。
Scenario 2
十进制值--124Hexadecimal值--0x7CgetYLHeight()应该返回7CgetYHHeight()应该返回0。
场景1工作正常,因为十六进制值是整数,但在场景2中,十六进制值7C不能转换为int。
有没有更好的方法来编写下面的代码,使其适用于这两种情况呢?
System.out.println("YL -" + hw.getYLHeight(400));//Hex value - 0x190,should return 90 - WORKS
System.out.println("YH -" + hw.getYHHeight(400));//Hex value - 0x190,should return 1 - WORKS
//System.out.println(hw.getYLHeight(124));//Hex value - 0x7C should return 7C - DOES NOT WORK
//System.out.println(hw.getYHHeight(124));//Hex value - 0x7C should return 0 - DOES NOT WORK
private byte getYLHeight(int height) {
int hexNewImageBytesLength = Integer.parseInt(Integer.toHexString(height));
byte yl = (byte)(hexNewImageBytesLength % 100);
return yl;
}
private byte getYHHeight(int height) {
int hexNewImageBytesLength = Integer.parseInt(Integer.toHexString(height));
byte yh = (byte)(hexNewImageBytesLength / 100);
return yh;
}
除以100肯定是错误的,应该是256,而不是100。
然而你不需要这样做。
private static byte getYLHeight(int height) {
return (byte) height;
}
private static byte getYHHeight(int height) {
return (byte) (height >>> 8);
}
要打印 byte
十六进制和十进制的值,使用 printf
:
System.out.printf("YL: hex=%1$02x, decimal=%1$d%n", Byte.toUnsignedInt(hw.getYLHeight(400)));
System.out.printf("YH: hex=%1$02x, decimal=%1$d%n", Byte.toUnsignedInt(hw.getYHHeight(400)));
产出
YL: hex=90, decimal=144
YH: hex=01, decimal=1
更新
如果你想让这些方法返回一个 String
与2位数的十六进制表示的 byte
的值,而不是这样做。
private static String getYLHeight(int height) {
return String.format("%02x", height & 0xFF);
}
private static String getYHHeight(int height) {
return String.format("%02x", (height >>> 8) & 0xFF);
}
测试
System.out.println("YL - " + hw.getYLHeight(400));
System.out.println("YH - " + hw.getYHHeight(400));
产量
YL - 90
YH - 01