【问题标题】:How to convert Decimal Value to hexadecimal in java?如何在java中将十进制值转换为十六进制?
【发布时间】:2015-03-13 18:11:47
【问题描述】:

如何在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);

}

【问题讨论】:

  • 首先是在stackoverflow数据库中搜索它是个好主意
  • @Stultuske 在这里我们应该使用 Java 提供的东西,所以这个特定的链接没有帮助。
  • 我认为这行不通,因为我需要将 -25.5 之类的值转换为十六进制。
  • @laune:我编辑了它。

标签: java hex decimal data-conversion


【解决方案1】:

从这段代码中尝试想法“请注意 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);
        }
    }

【讨论】:

  • 但是我应该在哪里传递我需要转换的值?
  • 并且输入是浮点数或双精度数
  • 通过使用扫描仪,控制台会要求您输入一个值,然后您可以指定它将采用什么类型 if double then double num =input.nextDouble(); see link.
  • @user3624028 然后 Integer.toHexString( num ) 会做什么......什么?
  • Integer.toHexString( num ) 将方法返回一个int的十六进制字符串表示,也可以将其赋值为double类型,例如:Double d = new Double("4.0"); String str = d.toHexString(1.0); System.out.println("Hex String = " + str);
【解决方案2】:

将温度以十分之一度表示为十六进制的有符号短(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;
}

这表示二进制补码中的整数,因此 -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;
}

【讨论】:

  • @launa :它对我不起作用。我正在传递输入 f:-54.9 但预期结果:0x8225
  • 但是我得到了 fbbd 结果。
  • 请阅读我写的内容。您是否坚持这种不同寻常的表现形式?
  • @AnkitKesarwani 我已经添加了符号幅度的方法。
  • @ laune :更新的解决方案对我有用。非常感谢劳恩。 :)
猜你喜欢
  • 2023-01-16
  • 2017-10-06
  • 1970-01-01
  • 2014-02-05
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
  • 2013-10-08
相关资源
最近更新 更多