PageRenderTime 49ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/AmpExt/dev/AmpExt/src/com/bhpb/AmplitudeExtraction/Format.java

https://bitbucket.org/glinsky/qiworkbench
Java | 620 lines | 438 code | 53 blank | 129 comment | 229 complexity | 080f145d6fa969a3555a562ca9ef28d3 MD5 | raw file
Possible License(s): BSD-3-Clause, Unlicense
  1. package com.bhpb.AmplitudeExtraction;
  2. import java.io.*;
  3. /**
  4. A class for formatting numbers that follows <tt>printf</tt> conventions.
  5. Also implements C-like <tt>atoi</tt> and <tt>atof</tt> functions
  6. @version 1.21 2000-06-09
  7. @author Cay Horstmann
  8. 1998-09-14: Fixed a number of bugs.
  9. 1.Formatting the most extreme negative number (-9223372036854775808L) printed with 2 leading minus signs.
  10. 2.Printing 0 with a %e or %g format did not work.
  11. 3.Printing numbers that were closer to 1 than the number of requested decimal places rounded down rather than up, e.g. formatting 1.999 with %.2f printed 1.00. (This one is pretty serious, of course.)
  12. 4.Printing with precision 0 (e.g %10.0f) didn't work.
  13. 5.Printing a string with a precision that exceeded the string length (e.g. print "Hello" with %20.10s) caused a StringIndexOutOfBounds error.
  14. 1998-10-21: Changed method names from print to printf
  15. 2000-06-09: Moved to package com.horstmann; no longer part of
  16. Core Java
  17. 2000-06-09: Fixed a number of bugs.
  18. 1.Printing 100.0 with %e printed 10.0e1, not 1.0e2
  19. 2.Printing Inf and NaN didn't work.
  20. 2000-06-09: Coding guideline cleanup
  21. */
  22. public class Format
  23. {
  24. /**
  25. Formats the number following <tt>printf</tt> conventions.
  26. Main limitation: Can only handle one format parameter at a time
  27. Use multiple Format objects to format more than one number
  28. @param s the format string following printf conventions
  29. The string has a prefix, a format code and a suffix. The prefix and suffix
  30. become part of the formatted output. The format code directs the
  31. formatting of the (single) parameter to be formatted. The code has the
  32. following structure
  33. <ul>
  34. <li> a % (required)
  35. <li> a modifier (optional)
  36. <dl>
  37. <dt> + <dd> forces display of + for positive numbers
  38. <dt> 0 <dd> show leading zeroes
  39. <dt> - <dd> align left in the field
  40. <dt> space <dd> prepend a space in front of positive numbers
  41. <dt> # <dd> use "alternate" format. Add 0 or 0x for octal or hexadecimal numbers. Don't suppress trailing zeroes in general floating point format.
  42. </dl>
  43. <li> an integer denoting field width (optional)
  44. <li> a period followed by an integer denoting precision (optional)
  45. <li> a format descriptor (required)
  46. <dl>
  47. <dt>f <dd> floating point number in fixed format
  48. <dt>e, E <dd> floating point number in exponential notation (scientific format). The E format results in an uppercase E for the exponent (1.14130E+003), the e format in a lowercase e.
  49. <dt>g, G <dd> floating point number in general format (fixed format for small numbers, exponential format for large numbers). Trailing zeroes are suppressed. The G format results in an uppercase E for the exponent (if any), the g format in a lowercase e.
  50. <dt>d, i <dd> integer in decimal
  51. <dt>x <dd> integer in hexadecimal
  52. <dt>o <dd> integer in octal
  53. <dt>s <dd> string
  54. <dt>c <dd> character
  55. </dl>
  56. </ul>
  57. @exception IllegalArgumentException if bad format
  58. */
  59. public Format(String s)
  60. {
  61. width = 0;
  62. precision = -1;
  63. pre = "";
  64. post = "";
  65. leadingZeroes = false;
  66. showPlus = false;
  67. alternate = false;
  68. showSpace = false;
  69. leftAlign = false;
  70. fmt = ' ';
  71. int state = 0;
  72. int length = s.length();
  73. int parseState = 0;
  74. // 0 = prefix, 1 = flags, 2 = width, 3 = precision,
  75. // 4 = format, 5 = end
  76. int i = 0;
  77. while (parseState == 0)
  78. {
  79. if (i >= length) parseState = 5;
  80. else if (s.charAt(i) == '%')
  81. {
  82. if (i < length - 1)
  83. {
  84. if (s.charAt(i + 1) == '%')
  85. {
  86. pre = pre + '%';
  87. i++;
  88. }
  89. else
  90. parseState = 1;
  91. }
  92. else throw new java.lang.IllegalArgumentException();
  93. }
  94. else
  95. pre = pre + s.charAt(i);
  96. i++;
  97. }
  98. while (parseState == 1)
  99. {
  100. if (i >= length) parseState = 5;
  101. else if (s.charAt(i) == ' ') showSpace = true;
  102. else if (s.charAt(i) == '-') leftAlign = true;
  103. else if (s.charAt(i) == '+') showPlus = true;
  104. else if (s.charAt(i) == '0') leadingZeroes = true;
  105. else if (s.charAt(i) == '#') alternate = true;
  106. else { parseState = 2; i--; }
  107. i++;
  108. }
  109. while (parseState == 2)
  110. {
  111. if (i >= length) parseState = 5;
  112. else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')
  113. {
  114. width = width * 10 + s.charAt(i) - '0';
  115. i++;
  116. }
  117. else if (s.charAt(i) == '.')
  118. {
  119. parseState = 3;
  120. precision = 0;
  121. i++;
  122. }
  123. else
  124. parseState = 4;
  125. }
  126. while (parseState == 3)
  127. {
  128. if (i >= length) parseState = 5;
  129. else if ('0' <= s.charAt(i) && s.charAt(i) <= '9')
  130. {
  131. precision = precision * 10 + s.charAt(i) - '0';
  132. i++;
  133. }
  134. else
  135. parseState = 4;
  136. }
  137. if (parseState == 4)
  138. {
  139. if (i >= length) parseState = 5;
  140. else fmt = s.charAt(i);
  141. i++;
  142. }
  143. if (i < length)
  144. post = s.substring(i, length);
  145. }
  146. /**
  147. prints a formatted number following printf conventions
  148. @param fmt the format string
  149. @param x the double to print
  150. */
  151. public static void printf(String fmt, double x)
  152. {
  153. System.out.print(new Format(fmt).format(x));
  154. }
  155. /**
  156. prints a formatted number following printf conventions
  157. @param fmt the format string
  158. @param x the int to print
  159. */
  160. public static void printf(String fmt, int x)
  161. {
  162. System.out.print(new Format(fmt).format(x));
  163. }
  164. /**
  165. prints a formatted number following printf conventions
  166. @param fmt the format string
  167. @param x the long to print
  168. */
  169. public static void printf(String fmt, long x)
  170. {
  171. System.out.print(new Format(fmt).format(x));
  172. }
  173. /**
  174. prints a formatted number following printf conventions
  175. @param fmt the format string
  176. @param x the character to print
  177. */
  178. public static void printf(String fmt, char x)
  179. {
  180. System.out.print(new Format(fmt).format(x));
  181. }
  182. /**
  183. prints a formatted number following printf conventions
  184. @param fmt the format string
  185. @param x a string to print
  186. */
  187. public static void printf(String fmt, String x)
  188. {
  189. System.out.print(new Format(fmt).format(x));
  190. }
  191. /**
  192. Converts a string of digits (decimal, octal or hex) to an integer
  193. @param s a string
  194. @return the numeric value of the prefix of s representing a base 10 integer
  195. */
  196. public static int atoi(String s)
  197. {
  198. return (int)atol(s);
  199. }
  200. /**
  201. Converts a string of digits (decimal, octal or hex) to a long integer
  202. @param s a string
  203. @return the numeric value of the prefix of s representing a base 10 integer
  204. */
  205. public static long atol(String s)
  206. {
  207. int i = 0;
  208. while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
  209. if (i < s.length() && s.charAt(i) == '0')
  210. {
  211. if (i + 1 < s.length() && (s.charAt(i + 1) == 'x' || s.charAt(i + 1) == 'X'))
  212. return parseLong(s.substring(i + 2), 16);
  213. else return parseLong(s, 8);
  214. }
  215. else return parseLong(s, 10);
  216. }
  217. private static long parseLong(String s, int base)
  218. {
  219. int i = 0;
  220. int sign = 1;
  221. long r = 0;
  222. while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
  223. if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }
  224. else if (i < s.length() && s.charAt(i) == '+') { i++; }
  225. while (i < s.length())
  226. {
  227. char ch = s.charAt(i);
  228. if ('0' <= ch && ch < '0' + base)
  229. r = r * base + ch - '0';
  230. else if ('A' <= ch && ch < 'A' + base - 10)
  231. r = r * base + ch - 'A' + 10 ;
  232. else if ('a' <= ch && ch < 'a' + base - 10)
  233. r = r * base + ch - 'a' + 10 ;
  234. else
  235. return r * sign;
  236. i++;
  237. }
  238. return r * sign;
  239. }
  240. /**
  241. Converts a string of digits to a <tt>double</tt>
  242. @param s a string
  243. */
  244. public static double atof(String s)
  245. {
  246. int i = 0;
  247. int sign = 1;
  248. double r = 0; // integer part
  249. double f = 0; // fractional part
  250. double p = 1; // exponent of fractional part
  251. int state = 0; // 0 = int part, 1 = frac part
  252. while (i < s.length() && Character.isWhitespace(s.charAt(i))) i++;
  253. if (i < s.length() && s.charAt(i) == '-') { sign = -1; i++; }
  254. else if (i < s.length() && s.charAt(i) == '+') { i++; }
  255. while (i < s.length())
  256. {
  257. char ch = s.charAt(i);
  258. if ('0' <= ch && ch <= '9')
  259. {
  260. if (state == 0)
  261. r = r * 10 + ch - '0';
  262. else if (state == 1)
  263. {
  264. p = p / 10;
  265. r = r + p * (ch - '0');
  266. }
  267. }
  268. else if (ch == '.')
  269. {
  270. if (state == 0) state = 1;
  271. else return sign * r;
  272. }
  273. else if (ch == 'e' || ch == 'E')
  274. {
  275. long e = (int)parseLong(s.substring(i + 1), 10);
  276. return sign * r * Math.pow(10, e);
  277. }
  278. else return sign * r;
  279. i++;
  280. }
  281. return sign * r;
  282. }
  283. /**
  284. Formats a <tt>double</tt> into a string (like sprintf in C)
  285. @param x the number to format
  286. @return the formatted string
  287. @exception IllegalArgumentException if bad argument
  288. */
  289. public String format(double x)
  290. {
  291. String r;
  292. if (precision < 0) precision = 6;
  293. int s = 1;
  294. if (x < 0) { x = -x; s = -1; }
  295. if (Double.isNaN(x)) r = "NaN";
  296. else if (x == Double.POSITIVE_INFINITY) r = "Inf";
  297. else if (fmt == 'f')
  298. r = fixedFormat(x);
  299. else if (fmt == 'e' || fmt == 'E' || fmt == 'g' || fmt == 'G')
  300. r = expFormat(x);
  301. else throw new java.lang.IllegalArgumentException();
  302. return pad(sign(s, r));
  303. }
  304. /**
  305. Formats an integer into a string (like sprintf in C)
  306. @param x the number to format
  307. @return the formatted string
  308. */
  309. public String format(int x)
  310. {
  311. long lx = x;
  312. if (fmt == 'o' || fmt == 'x' || fmt == 'X')
  313. lx &= 0xFFFFFFFFL;
  314. return format(lx);
  315. }
  316. /**
  317. Formats a long integer into a string (like sprintf in C)
  318. @param x the number to format
  319. @return the formatted string
  320. */
  321. public String format(long x)
  322. {
  323. String r;
  324. int s = 0;
  325. if (fmt == 'd' || fmt == 'i')
  326. {
  327. if (x < 0)
  328. {
  329. r = ("" + x).substring(1);
  330. s = -1;
  331. }
  332. else
  333. {
  334. r = "" + x;
  335. s = 1;
  336. }
  337. }
  338. else if (fmt == 'o')
  339. r = convert(x, 3, 7, "01234567");
  340. else if (fmt == 'x')
  341. r = convert(x, 4, 15, "0123456789abcdef");
  342. else if (fmt == 'X')
  343. r = convert(x, 4, 15, "0123456789ABCDEF");
  344. else throw new java.lang.IllegalArgumentException();
  345. return pad(sign(s, r));
  346. }
  347. /**
  348. Formats a character into a string (like sprintf in C)
  349. @param x the value to format
  350. @return the formatted string
  351. */
  352. public String format(char c)
  353. {
  354. if (fmt != 'c')
  355. throw new java.lang.IllegalArgumentException();
  356. String r = "" + c;
  357. return pad(r);
  358. }
  359. /**
  360. Formats a string into a larger string (like sprintf in C)
  361. @param x the value to format
  362. @return the formatted string
  363. */
  364. public String format(String s)
  365. {
  366. if (fmt != 's')
  367. throw new java.lang.IllegalArgumentException();
  368. if (precision >= 0 && precision < s.length())
  369. s = s.substring(0, precision);
  370. return pad(s);
  371. }
  372. /**
  373. a test stub for the format class
  374. */
  375. public static void main(String[] a)
  376. {
  377. double x = 1.23456789012;
  378. double y = 123;
  379. double z = 1.2345e30;
  380. double w = 1.02;
  381. double u = 1.234e-5;
  382. int d = 0xCAFE;
  383. Format.printf("x = |%f|\n", x);
  384. Format.printf("u = |%20f|\n", u);
  385. Format.printf("x = |% .5f|\n", x);
  386. Format.printf("w = |%20.5f|\n", w);
  387. Format.printf("x = |%020.5f|\n", x);
  388. Format.printf("x = |%+20.5f|\n", x);
  389. Format.printf("x = |%+020.5f|\n", x);
  390. Format.printf("x = |% 020.5f|\n", x);
  391. Format.printf("y = |%#+20.5f|\n", y);
  392. Format.printf("y = |%-+20.5f|\n", y);
  393. Format.printf("z = |%20.5f|\n", z);
  394. Format.printf("x = |%e|\n", x);
  395. Format.printf("u = |%20e|\n", u);
  396. Format.printf("x = |% .5e|\n", x);
  397. Format.printf("w = |%20.5e|\n", w);
  398. Format.printf("x = |%020.5e|\n", x);
  399. Format.printf("x = |%+20.5e|\n", x);
  400. Format.printf("x = |%+020.5e|\n", x);
  401. Format.printf("x = |% 020.5e|\n", x);
  402. Format.printf("y = |%#+20.5e|\n", y);
  403. Format.printf("y = |%-+20.5e|\n", y);
  404. Format.printf("x = |%g|\n", x);
  405. Format.printf("z = |%g|\n", z);
  406. Format.printf("w = |%g|\n", w);
  407. Format.printf("u = |%g|\n", u);
  408. Format.printf("y = |%.2g|\n", y);
  409. Format.printf("y = |%#.2g|\n", y);
  410. Format.printf("d = |%d|\n", d);
  411. Format.printf("d = |%20d|\n", d);
  412. Format.printf("d = |%020d|\n", d);
  413. Format.printf("d = |%+20d|\n", d);
  414. Format.printf("d = |% 020d|\n", d);
  415. Format.printf("d = |%-20d|\n", d);
  416. Format.printf("d = |%20.8d|\n", d);
  417. Format.printf("d = |%x|\n", d);
  418. Format.printf("d = |%20X|\n", d);
  419. Format.printf("d = |%#20x|\n", d);
  420. Format.printf("d = |%020X|\n", d);
  421. Format.printf("d = |%20.8x|\n", d);
  422. Format.printf("d = |%o|\n", d);
  423. Format.printf("d = |%020o|\n", d);
  424. Format.printf("d = |%#20o|\n", d);
  425. Format.printf("d = |%#020o|\n", d);
  426. Format.printf("d = |%20.12o|\n", d);
  427. Format.printf("s = |%-20s|\n", "Hello");
  428. Format.printf("s = |%-20c|\n", '!');
  429. // regression test to confirm fix of reported bugs
  430. Format.printf("|%i|\n", Long.MIN_VALUE);
  431. Format.printf("|%6.2e|\n", 0.0);
  432. Format.printf("|%6.2g|\n", 0.0);
  433. Format.printf("|%6.2f|\n", 9.99);
  434. Format.printf("|%6.2f|\n", 9.999);
  435. Format.printf("|%.2f|\n", 1.999);
  436. Format.printf("|%6.0f|\n", 9.999);
  437. Format.printf("|%20.10s|\n", "Hello");
  438. d = -1;
  439. Format.printf("-1 = |%X|\n", d);
  440. Format.printf("100 = |%e|\n", 100.0); // 2000-06-09
  441. Format.printf("1/0 = |%f|\n", 1.0 / 0.0);
  442. Format.printf("-1/0 = |%e|\n", -1.0 / 0.0);
  443. Format.printf("0/0 = |%g|\n", 0.0 / 0.0);
  444. }
  445. private static String repeat(char c, int n)
  446. {
  447. if (n <= 0) return "";
  448. StringBuffer s = new StringBuffer(n);
  449. for (int i = 0; i < n; i++) s.append(c);
  450. return s.toString();
  451. }
  452. private static String convert(long x, int n, int m, String d)
  453. {
  454. if (x == 0) return "0";
  455. String r = "";
  456. while (x != 0)
  457. {
  458. r = d.charAt((int)(x & m)) + r;
  459. x = x >>> n;
  460. }
  461. return r;
  462. }
  463. private String pad(String r)
  464. {
  465. String p = repeat(' ', width - r.length());
  466. if (leftAlign) return pre + r + p + post;
  467. else return pre + p + r + post;
  468. }
  469. private String sign(int s, String r)
  470. {
  471. String p = "";
  472. if (s < 0) p = "-";
  473. else if (s > 0)
  474. {
  475. if (showPlus) p = "+";
  476. else if (showSpace) p = " ";
  477. }
  478. else
  479. {
  480. if (fmt == 'o' && alternate && r.length() > 0 && r.charAt(0) != '0') p = "0";
  481. else if (fmt == 'x' && alternate) p = "0x";
  482. else if (fmt == 'X' && alternate) p = "0X";
  483. }
  484. int w = 0;
  485. if (leadingZeroes)
  486. w = width;
  487. else if ((fmt == 'd' || fmt == 'i' || fmt == 'x' || fmt == 'X' || fmt == 'o')
  488. && precision > 0) w = precision;
  489. return p + repeat('0', w - p.length() - r.length()) + r;
  490. }
  491. private String fixedFormat(double d)
  492. {
  493. boolean removeTrailing
  494. = (fmt == 'G' || fmt == 'g') && !alternate;
  495. // remove trailing zeroes and decimal point
  496. if (d > 0x7FFFFFFFFFFFFFFFL) return expFormat(d);
  497. if (precision == 0)
  498. return (long)(d + 0.5) + (removeTrailing ? "" : ".");
  499. long whole = (long)d;
  500. double fr = d - whole; // fractional part
  501. if (fr >= 1 || fr < 0) return expFormat(d);
  502. double factor = 1;
  503. StringBuffer leadingZeroes = new StringBuffer();
  504. for (int i = 1; i <= precision && factor <= 0x7FFFFFFFFFFFFFFFL; i++)
  505. {
  506. factor *= 10;
  507. leadingZeroes.append("0");
  508. }
  509. long l = (long) (factor * fr + 0.5);
  510. if (l >= factor) { l = 0; whole++; } // CSH 10-25-97
  511. String z = leadingZeroes.toString() + l;
  512. z = "." + z.substring(z.length() - precision, z.length());
  513. if (removeTrailing)
  514. {
  515. int t = z.length() - 1;
  516. while (t >= 0 && z.charAt(t) == '0') t--;
  517. if (t >= 0 && z.charAt(t) == '.') t--;
  518. z = z.substring(0, t + 1);
  519. }
  520. return whole + z;
  521. }
  522. private String expFormat(double d)
  523. {
  524. String f = "";
  525. int e = 0;
  526. double dd = d;
  527. double factor = 1;
  528. if (d != 0)
  529. {
  530. while (dd >= 10) { e++; factor /= 10; dd = dd / 10; } // 2000-06-09
  531. while (dd < 1) { e--; factor *= 10; dd = dd * 10; }
  532. }
  533. if ((fmt == 'g' || fmt == 'G') && e >= -4 && e < precision)
  534. return fixedFormat(d);
  535. d = d * factor;
  536. f = f + fixedFormat(d);
  537. if (fmt == 'e' || fmt == 'g')
  538. f = f + "e";
  539. else
  540. f = f + "E";
  541. String p = "000";
  542. if (e >= 0)
  543. {
  544. f = f + "+";
  545. p = p + e;
  546. }
  547. else
  548. {
  549. f = f + "-";
  550. p = p + (-e);
  551. }
  552. return f + p.substring(p.length() - 3, p.length());
  553. }
  554. private int width;
  555. private int precision;
  556. private String pre;
  557. private String post;
  558. private boolean leadingZeroes;
  559. private boolean showPlus;
  560. private boolean alternate;
  561. private boolean showSpace;
  562. private boolean leftAlign;
  563. private char fmt; // one of cdeEfgGiosxXos
  564. }