簡體   English   中英

如何在 java 中將十六進制值轉換為字節

[英]How to convert Hexadecimal value to byte in java

我編寫了兩個函數,它們接受 integer 將其轉換為十六進制值並返回字節值。

例如

Scenario 1十進制值 - 400 十六進制值 - 0x190 getYLHeight() 應返回 90 getYHHeight() 應返回 1

Scenario 2十進制值 - 124 十六進制值 - 0x7C getYLHeight() 應返回 7C getYHHeight() 應返回 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)));

Output

YL: hex=90, decimal=144
YH: hex=01, decimal=1

更新

如果您希望方法返回具有byte值的 2 位十六進制表示的String ,請改為執行以下操作:

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));

Output

YL - 90
YH - 01

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM