0

Looking for a solution to resolve my problem, I've found just Hex signed to int value transformation, but not the inverse case.

I've tried this:

  float grades = -32.33f ;
  System.out.println("grades: "+grades);

  double radians = Math.toRadians(grades);
  System.out.println("rad: "+radians);

  radians = radians * 100000000;
  System.out.println("rad * 10^8: "+radians);

  String hex = Double.toHexString(radians);
  System.out.println("signed to hex: "+hex);

with output:

grados: -32.33
rad: -0.5642649791276998
rad * 10^8: -5.642649791276998E7
signed to hex: -0x1.ae8000f4d5a59p25

But I'm expecting get:

FCA30001

In this answer Java negative int to hex and back fails I found that Double.toHexString(radians); gave me an unsgined value, may be this is the problem. Any Ideas?

Thanks in advance.

EDIT:

I'm trying do the inverse operation of:

  • 1) FCA30001 to signed int is: -56426495,
  • 2) -56426495*10^8 is -0.564264 radians,
  • 3) Now converting radians to grades is -32.33.
Community
  • 1
  • 1
hcarrasko
  • 2,320
  • 6
  • 33
  • 45

1 Answers1

0

Checking long/int overflow: 108 needs 23 bits + 2π 3 bits < 32, so int is fine.

long radiansUp8 = 0xFFFF_FFFFL & (long)(radians * 100_000_000);
String hex = Long.toHexString(radiansUp8);

Though we took an int, because of the sign, it was placed in a long, and masked with Integer.MAX_VALUE.


For precision:

As you know double is only an approximation of a sum of powers of 2. Multiplying by 108 enlarges the approximation error. And in your code even 4 bytes float is used.

double grades = -32.33;

should be a bit better.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Thanks, I test this code, but the finnal output is `signed to hex: fca2ffff`, in some part I'm losing digits may be. I'm expecting get `fca30001` – hcarrasko Apr 10 '15 at 12:59
  • The approximation error of the initial grades is multiplied by more that 108. Added a hint to the answer. – Joop Eggen Apr 10 '15 at 13:35