fork download
  1. class Test {
  2.  
  3. private static String toDecimal(String hex, int numberDigits) {
  4. /* converts a string such as "13.1a" in base 16 to "19.1015625" in base 10 */
  5. int index = hex.indexOf('.');
  6. assert index != -1;
  7. StringBuilder decimal = new StringBuilder((index == 0) ? "" : String.valueOf(Integer.parseInt(hex.substring(0, index), 16)));
  8. decimal.append('.');
  9. int l = hex.length() - index - 1;
  10. assert l >= 1;
  11. int firstIndex = index + 1;
  12. int hexDigits[] = new int[l];
  13. for (int i = 0; i < l; i++) {
  14. hexDigits[i] = Integer.parseInt(hex.substring(i + firstIndex, i + firstIndex + 1), 16);
  15. }
  16. while (numberDigits != 0 && l != 0) {
  17. int carry = 0;
  18. boolean allZeroes = true;
  19. for (int i = l - 1; i >= 0; i--) {
  20. int value = hexDigits[i] * 10 + carry;
  21. if (value == 0 && allZeroes) {
  22. l = i;
  23. }
  24. else {
  25. allZeroes = false;
  26. carry = (int)(value / 16);
  27. hexDigits[i] = value % 16;
  28. }
  29. }
  30. numberDigits--;
  31. if (carry != 0 || (numberDigits != 0 && l != 0))
  32. decimal.append("0123456789".charAt(carry));
  33. }
  34. return decimal.toString();
  35. }
  36.  
  37. public static void main(String[] args) {
  38. System.out.println(toDecimal("13.1a", 15));
  39. System.out.println(toDecimal("13.8", 15));
  40. System.out.println(toDecimal("13.1234", 15));
  41. }
  42.  
  43. }
Success #stdin #stdout 0.06s 32440KB
stdin
Standard input is empty
stdout
19.1015625
19.5
19.07110595703125