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

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

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

  1. private static double hexDataToTemperature(String tempHexData) {
  2. String tempMSBstr = tempHexData.substring(0, 2);
  3. String tempLSBstr = tempHexData.substring(2, 4);
  4. int tempMSB = Integer.parseInt(tempMSBstr, 16);
  5. int tempLSB = Integer.parseInt(tempLSBstr, 16);
  6. int sign = 1;
  7. if (tempMSB >= 128) {
  8. tempMSB = tempMSB - 128;
  9. sign = -1;
  10. }
  11. Float f = (float) (sign * ((float) ((tempMSB * 256) + tempLSB) / 10));
  12. return Double.parseDouble("" + f);
  13. }
krcsximq

krcsximq1#

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

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

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

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

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

  1. static String toHex( float t ){
  2. int sign = 0;
  3. if( t < 0 ){
  4. sign = 0x8000;
  5. t = -t;
  6. }
  7. short it = (short)(Math.round(t*10) + sign);
  8. return String.format( "%04x", it );
  9. }
  10. static float toDec( String s ){
  11. int it = Integer.parseInt( s, 16 );
  12. if( it > 32767 ){
  13. it = -(it - 0x8000);
  14. }
  15. return it/10.0F;
  16. }
展开查看全部
vfh0ocws

vfh0ocws2#

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

  1. import java.util.Scanner;
  2. class DecimalToHex
  3. {
  4. public static void main(String args[])
  5. {
  6. Scanner input = new Scanner( System.in );
  7. System.out.print(" decimal number : ");
  8. int num =input.nextInt();
  9. // calling method toHexString()
  10. String str = Integer.toHexString(num);
  11. System.out.println("Decimal to hexadecimal: "+str);
  12. }
  13. }

相关问题