home *** CD-ROM | disk | FTP | other *** search
/ Liren Large Software Subsidy 10 / 10.iso / l / l460 / 2.ddi / STRFUN.DI$ / HEX2NUM.M < prev    next >
Encoding:
Text File  |  1993-03-07  |  1.3 KB  |  48 lines

  1. function x = hex2num(s)
  2. %HEX2NUM IEEE hexadecimal to double precision number conversion.
  3. %    HEX2NUM(S), where S is a 16 character string containing
  4. %    a hexadecimal number, returns the IEEE double precision
  5. %    floating point number it represents.  Fewer than 16
  6. %    characters are padded on the right with zeros.
  7. %
  8. %    For example, HEX2NUM('400921fb54442d18') returns Pi.
  9. %                 HEX2NUM('bff') returns -1.
  10. %
  11. %    NaNs, infinities and denorms are handled correctly.  See
  12. %    also FORMAT HEX.
  13.  
  14. %    C.B. Moler 12-18-87, 1-5-88, 9-17-91.
  15. %    Copyright (c) 1984-93 by The MathWorks, Inc.
  16.  
  17. if ~isstr(s)
  18.     error('Input to hex2num must be a string.')
  19. end
  20.  
  21. % Convert characters to numeric digits.
  22. % More than 16 characters are truncated.
  23. d = zeros(1,16);
  24. d(1:length(s)) = abs(lower(s)) - '0';
  25. d = d + ('0'+10-'a').*(d>10);
  26. neg = d(1) > 7;
  27. if neg, d(1) = d(1)-8; end
  28. if any(d > 15) | any(d < 0)
  29.     error('Input string to hex2num should have just 0-9, a-f, or A-F.')
  30. end
  31.  
  32. % Floating point exponent.
  33. e = 16*(16*(d(1)-4) + d(2)) + d(3) + 1;
  34.  
  35. % Floating point fraction.
  36. f = 0;
  37. for i = 16:-1:4, f = (f + d(i))/16; end
  38.  
  39. % Scale the fraction by 2 to the exponent.
  40. if e > 1023
  41.    if f == 0, x = inf; else, x = NaN; end
  42. elseif e < -1022
  43.    x = pow2(f,-1022);
  44. else
  45.    x = pow2(1 + f, e);
  46. end
  47. if neg, x = -x; end
  48.