如何在java中将十进制值转换为十六进制?

3wabscal  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(434)

如何在java中将十进制值(温度)转换为16位十六进制?
输入:-54.9
预期结果:0x8225
我有相反的代码,我把16字节的十六进制转换成十进制值(温度)。

private static double hexDataToTemperature(String tempHexData) {

    String tempMSBstr = tempHexData.substring(0, 2);
    String tempLSBstr = tempHexData.substring(2, 4);

    int tempMSB = Integer.parseInt(tempMSBstr, 16);
    int tempLSB = Integer.parseInt(tempLSBstr, 16);
    int sign = 1;

    if (tempMSB >= 128) {
        tempMSB = tempMSB - 128;
        sign = -1;
    }

    Float f = (float) (sign * ((float) ((tempMSB * 256) + tempLSB) / 10));

    return Double.parseDouble("" + f);

}
krcsximq

krcsximq1#

用十六进制表示的有符号短(16位)值表示十分之一度的温度:

static String toHex( float t ){
    short it = (short)Math.round(t*10);
    return String.format( "%04x", it );
}

如果需要,可以在格式字符串中添加“0x”。-反向转换:

static float toDec( String s ){
    int it = Integer.parseInt( s, 16 );
    if( it > 32767 ) it -= 65536;
    return it/10.0F;
}

这表示2的补码中的整数,因此-54.9的结果将不是0x8225而是0xfddb。使用最高有效位作为符号位并表示剩余15位中的绝对值(“有符号幅度”)是非常不寻常的,尤其是在java中。
如果要使用有符号幅值:

static String toHex( float t ){
    int sign = 0;
    if( t < 0 ){
        sign = 0x8000;
        t = -t;
    }
    short it = (short)(Math.round(t*10) + sign);
    return String.format( "%04x", it );
}

static float toDec( String s ){
    int it = Integer.parseInt( s, 16 );
    if( it > 32767 ){
        it = -(it - 0x8000);
    }
    return it/10.0F;
}
vfh0ocws

vfh0ocws2#

试试下面的代码“please notice tohexstring()”中的想法

import java.util.Scanner;
    class DecimalToHex
    {
        public static void main(String args[])
        {
          Scanner input = new Scanner( System.in );
          System.out.print(" decimal number : ");
          int num =input.nextInt();

          // calling method toHexString()
          String str = Integer.toHexString(num);
          System.out.println("Decimal to hexadecimal: "+str);
        }
    }

相关问题