3Copyright (C) 2008, 2009 David Bateman
5This file is part of Octave.
7Octave is free software; you can redistribute it and/or modify it
8under the terms of the GNU General Public License as published by the
9Free Software Foundation; either version 3 of the License, or (at your
10option) any later version.
12Octave is distributed in the hope that it will be useful, but WITHOUT
13ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17You should have received a copy of the GNU General Public License
18along with Octave; see the file COPYING. If not, see
19<http://www.gnu.org/licenses/>.
35DEFUN_DLD (hex2num, args, ,
37@deftypefn {Loadable Function} {@var{n} =} hex2num (@var{s})\n\
38Typecast the 16 character hexadecimal character matrix to an IEEE 754\n\
39double precision number. If fewer than 16 characters are given the\n\
40strings are right padded with '0' characters.\n\
42Given a string matrix, @code{hex2num} treats each row as a separate\n\
47hex2num ([\"4005bf0a8b145769\";\"4024000000000000\"])\n\
48@result{} [2.7183; 10.000]\n\
51@seealso{num2hex, hex2dec, dec2hex}\n\
54 int nargin = args.length ();
61 const charMatrix cmat = args(0).char_matrix_value ();
63 if (cmat.columns () > 16)
64 error ("hex2num: expecting no more than a 16 character string");
65 else if (! error_state)
67 octave_idx_type nr = cmat.rows ();
68 octave_idx_type nc = cmat.columns ();
71 for (octave_idx_type i = 0; i < nr; i++)
79 for (octave_idx_type j = 0; j < nc; j++)
81 unsigned char ch = cmat.elem (i, j);
87 num.ival += static_cast<uint64_t> (ch - 'a' + 10);
89 num.ival += static_cast<uint64_t> (ch - 'A' + 10);
91 num.ival += static_cast<uint64_t> (ch - '0');
95 error ("hex2num: illegal character found in string");
105 num.ival <<= (16 - nc) * 4;
120%!assert (hex2num(['c00';'bff';'000';'3ff';'400']),[-2:2]')
123DEFUN_DLD (num2hex, args, ,
125@deftypefn {Loadable Function} {@var{s} =} num2hex (@var{n})\n\
126Typecast a double precision number or vector to a 16 character hexadecimal\n\
127string of the IEEE 754 representation of the number. For example\n\
131num2hex ([-1, 1, e, Inf, NaN, NA]);\n\
132@result{} \"bff0000000000000\n\
137 7ff00000000007a2\"\n\
140@seealso{hex2num, hex2dec, dec2hex}\n\
143 int nargin = args.length ();
150 const ColumnVector v (args(0).vector_value ());
154 octave_idx_type nr = v.length ();
155 charMatrix m (nr, 16);
156 const double *pv = v.fortran_vec ();
158 for (octave_idx_type i = 0; i < nr; i++)
168 for (octave_idx_type j = 0; j < 16; j++)
171 static_cast<char> (num.ival >> ((15 - j) * 4) & 0xF);
189%!assert (num2hex (-2:2),['c000000000000000';'bff0000000000000';'0000000000000000';'3ff0000000000000';'4000000000000000'])