GNU Octave  4.4.1
A high-level interpreted language, primarily intended for numerical computations, mostly compatible with Matlab
hex2num.cc
Go to the documentation of this file.
1 /*
2 
3 Copyright (C) 2017-2018 John W. Eaton
4 Copyright (C) 2008-2018 David Bateman
5 
6 This file is part of Octave.
7 
8 Octave is free software: you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12 
13 Octave is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17 
18 You should have received a copy of the GNU General Public License
19 along with Octave; see the file COPYING. If not, see
20 <https://www.gnu.org/licenses/>.
21 
22 */
23 
24 #if defined (HAVE_CONFIG_H)
25 # include "config.h"
26 #endif
27 
28 #include "defun.h"
29 #include "error.h"
30 #include "errwarn.h"
31 #include "mach-info.h"
32 #include "ov.h"
33 #include "ovl.h"
34 #include "utils.h"
35 
36 static inline bool
37 is_little_endian (bool is_float)
38 {
39  return ((is_float && (octave::mach_info::native_float_format ()
42 }
43 
44 static uint8_t
45 hex2nibble (unsigned char ch)
46 {
47  unsigned char val = 0;
48 
49  if (! isxdigit (ch))
50  error ("hex2num: invalid character '%c' found in string S", ch);
51 
52  if (ch >= 'a')
53  val = static_cast<unsigned char> (ch - 'a' + 10);
54  else if (ch >= 'A')
55  val = static_cast<unsigned char> (ch - 'A' + 10);
56  else
57  val = static_cast<unsigned char> (ch - '0');
58 
59  return val;
60 }
61 
62 static void
63 hex2num (const std::string& hex, void *num, size_t nbytes, bool swap_bytes)
64 {
65  unsigned char *cp = reinterpret_cast<unsigned char *> (num);
66 
67  const size_t nc = hex.length ();
68  const size_t nchars = 2 * nbytes;
69 
70  if (nc > nchars)
71  error ("hex2num: S must be no more than %d characters", nchars);
72 
73  size_t j = 0;
74 
75  for (size_t i = 0; i < nbytes; i++)
76  {
77  size_t k = (swap_bytes ? nbytes - i - 1 : i);
78 
79  unsigned char ch1 = (j < nc) ? hex[j++] : '0';
80  unsigned char ch2 = (j < nc) ? hex[j++] : '0';
81 
82  cp[k] = (hex2nibble (ch1) << 4) + hex2nibble (ch2);
83  }
84 }
85 
86 template <typename T>
89 {
90  octave_idx_type nel = val.numel ();
91 
92  Array<T> m (val.dims ());
93 
94  size_t nbytes = sizeof (T);
95 
96  for (octave_idx_type i = 0; i < nel; i++)
97  {
98  T num;
99 
100  hex2num (val.xelem (i), &num, nbytes, swap_bytes);
101 
102  m(i) = num;
103  }
104 
105  return m;
106 }
107 
108 DEFUN (hex2num, args, ,
109  doc: /* -*- texinfo -*-
110 @deftypefn {} {@var{n} =} hex2num (@var{s})
111 @deftypefnx {} {@var{n} =} hex2num (@var{s}, @var{class})
112 Typecast a hexadecimal character array or cell array of strings to an
113 array of numbers.
114 
115 By default, the input array is interpreted as a hexadecimal number
116 representing a double precision value. If fewer than 16 characters are
117 given the strings are right padded with @qcode{'0'} characters.
118 
119 Given a string matrix, @code{hex2num} treats each row as a separate number.
120 
121 @example
122 @group
123 hex2num (["4005bf0a8b145769"; "4024000000000000"])
124  @result{} [2.7183; 10.000]
125 @end group
126 @end example
127 
128 The optional second argument @var{class} may be used to cause the input
129 array to be interpreted as a different value type. Possible values are
130 
131 @multitable {Option} {Characters}
132 @headitem Option @tab Characters
133 @item @qcode{"int8"} @tab 2
134 @item @qcode{"uint8"} @tab 2
135 @item @qcode{"int16"} @tab 4
136 @item @qcode{"uint16"} @tab 4
137 @item @qcode{"int32"} @tab 8
138 @item @qcode{"uint32"} @tab 8
139 @item @qcode{"int64"} @tab 16
140 @item @qcode{"uint64"} @tab 16
141 @item @qcode{"char"} @tab 2
142 @item @qcode{"single"} @tab 8
143 @item @qcode{"double"} @tab 16
144 @end multitable
145 
146 For example:
147 
148 @example
149 @group
150 hex2num (["402df854"; "41200000"], "single")
151  @result{} [2.7183; 10.000]
152 @end group
153 @end example
154 @seealso{num2hex, hex2dec, dec2hex}
155 @end deftypefn */)
156 {
158 
159  int nargin = args.length ();
160 
162  print_usage ();
163 
164  std::string type = "double";
165  if (nargin == 2)
166  type = args(1).xstring_value ("hex2num: CLASS must be a string");
167 
168  Array<std::string> val = args(0).cellstr_value ();
169 
170  // We always use big-endian order for hex digits.
171  bool is_float = type == "single" || type == "double";
172  bool swap_bytes = is_little_endian (is_float);
173 
174  if (type == "int8")
175  retval = octave_value (hex2num<octave_int8> (val, swap_bytes));
176  else if (type == "uint8")
177  retval = octave_value (hex2num<octave_uint8> (val, swap_bytes));
178  else if (type == "int16")
179  retval = octave_value (hex2num<octave_int16> (val, swap_bytes));
180  else if (type == "uint16")
181  retval = octave_value (hex2num<octave_uint16> (val, swap_bytes));
182  else if (type == "int32")
183  retval = octave_value (hex2num<octave_int32> (val, swap_bytes));
184  else if (type == "uint32")
185  retval = octave_value (hex2num<octave_uint32> (val, swap_bytes));
186  else if (type == "int64")
187  retval = octave_value (hex2num<octave_int64> (val, swap_bytes));
188  else if (type == "uint64")
189  retval = octave_value (hex2num<octave_uint64> (val, swap_bytes));
190  else if (type == "char")
191  retval = octave_value (hex2num<char> (val, swap_bytes));
192  else if (type == "single")
193  retval = octave_value (hex2num<float> (val, swap_bytes));
194  else if (type == "double")
195  retval = octave_value (hex2num<double> (val, swap_bytes));
196  else
197  error ("hex2num: unrecognized CLASS '%s'", type.c_str ());
198 
199  return retval;
200 }
201 
202 /*
203 %!assert (hex2num (["c00";"bff";"000";"3ff";"400"]), [-2:2]')
204 %!assert (hex2num (["c00";"bf8";"000";"3f8";"400"], "single"), single([-2:2])')
205 %!assert (hex2num ("ff", "uint8"), intmax ("uint8"))
206 %!assert (hex2num ("ffff", "uint16"), intmax ("uint16"))
207 %!assert (hex2num ("ffffffff", "uint32"), intmax ("uint32"))
208 %!assert (hex2num ("ffffffff", "uint32"), intmax ("uint32"))
209 %!assert (hex2num ("ffffffffffffffff", "uint64"), intmax ("uint64"))
210 */
211 
212 static inline unsigned char
213 nibble2hex (unsigned char ch)
214 {
215  if (ch >= 10)
216  ch += 'a' - 10;
217  else
218  ch += '0';
219 
220  return ch;
221 }
222 
223 static inline void
224 num2hex (const void *p, size_t n, char *hex, bool swap_bytes)
225 {
226  const unsigned char *cp = reinterpret_cast<const unsigned char *> (p);
227 
228  size_t k = 0;
229 
230  for (size_t i = 0; i < n; i++)
231  {
232  size_t j = (swap_bytes ? n - i - 1 : i);
233 
234  unsigned char ch = cp[j];
235 
236  hex[k++] = nibble2hex ((ch >> 4) & 0xF);
237  hex[k++] = nibble2hex (ch & 0xF);
238  }
239 }
240 
241 template <typename T>
242 Cell
243 num2hex (const Array<T>& v, bool swap_bytes)
244 {
245  const size_t nbytes = sizeof (T);
246  const size_t nchars = 2 * nbytes;
247 
248  octave_idx_type nel = v.numel ();
249 
250  string_vector sv (nel);
251 
252  const T *pv = v.fortran_vec ();
253 
254  for (octave_idx_type i = 0; i < nel; i++)
255  {
256  char hex[nchars];
257 
258  num2hex (pv++, nbytes, hex, swap_bytes);
259 
260  sv[i] = std::string (hex, nchars);
261  }
262 
263  return Cell (v.dims (), sv);
264 }
265 
266 DEFUN (num2hex, args, ,
267  doc: /* -*- texinfo -*-
268 @deftypefn {} {@var{s} =} num2hex (@var{n})
269 @deftypefnx {} {@var{s} =} num2hex (@var{n}, "cell")
270 Convert a numeric array to an array of hexadecimal strings.
271 
272 For example:
273 
274 @example
275 @group
276 num2hex ([-1, 1, e, Inf])
277 @result{} "bff0000000000000
278  3ff0000000000000
279  4005bf0a8b145769
280  7ff0000000000000"
281 @end group
282 @end example
283 
284 If the argument @var{n} is a single precision number or vector, the returned
285 string has a length of 8. For example:
286 
287 @example
288 @group
289 num2hex (single ([-1, 1, e, Inf]))
290 @result{} "bf800000
291  3f800000
292  402df854
293  7f800000"
294 @end group
295 @end example
296 
297 With the optional second argument @qcode{"cell"}, return a cell array of
298 strings instead of a character array.
299 @seealso{hex2num, hex2dec, dec2hex}
300 @end deftypefn */)
301 {
302  int nargin = args.length ();
303 
305  print_usage ();
306 
307  bool as_cell = false;
308 
309  if (nargin == 2)
310  {
311  std::string opt = args(1).xstring_value ("num2hex: second argument must be a string");
312  if (opt == "cell")
313  as_cell = true;
314  else
315  error ("num2hex: unrecognized option '%s'", opt.c_str ());
316  }
317 
318  octave_value val = args(0);
319 
320  if (val.iscomplex ())
321  error ("num2hex: N must be real");
322 
323  Cell result;
324 
325  // We always use big-endian order for hex digits.
326  bool is_float = val.is_single_type () || val.is_double_type ();
327  bool swap_bytes = is_little_endian (is_float);
328 
329  if (val.is_int8_type ())
330  result = num2hex (val.int8_array_value (), swap_bytes);
331  else if (val.is_int16_type ())
332  result = num2hex<octave_int16> (val.int16_array_value (), swap_bytes);
333  else if (val.is_int32_type ())
334  result = num2hex<octave_int32> (val.int32_array_value (), swap_bytes);
335  else if (val.is_int64_type ())
336  result = num2hex<octave_int64> (val.int64_array_value (), swap_bytes);
337  else if (val.is_uint8_type ())
338  result = num2hex<octave_uint8> (val.uint8_array_value (), swap_bytes);
339  else if (val.is_uint16_type ())
340  result = num2hex<octave_uint16> (val.uint16_array_value (), swap_bytes);
341  else if (val.is_uint32_type ())
342  result = num2hex<octave_uint32> (val.uint32_array_value (), swap_bytes);
343  else if (val.is_uint64_type ())
344  result = num2hex<octave_uint64> (val.uint64_array_value (), swap_bytes);
345  else if (val.is_char_matrix ())
346  result = num2hex<char> (val.char_array_value (), swap_bytes);
347  else if (val.is_single_type ())
348  result = num2hex<float> (val.float_vector_value (), swap_bytes);
349  else if (val.is_double_type ())
350  result = num2hex<double> (val.vector_value (), swap_bytes);
351  else
352  err_wrong_type_arg ("num2hex", val);
353 
354  return (as_cell
355  ? octave_value (result)
356  : octave_value (result.string_vector_value ()));
357 }
358 
359 /*
360 %!assert (num2hex (-2:2), ["c000000000000000";"bff0000000000000";"0000000000000000";"3ff0000000000000";"4000000000000000"])
361 %!assert (num2hex (single (-2:2)), ["c0000000";"bf800000";"00000000";"3f800000";"40000000"])
362 %!assert (num2hex (intmax ("uint8")), "ff")
363 %!assert (num2hex (intmax ("uint16")), "ffff")
364 %!assert (num2hex (intmax ("uint32")), "ffffffff")
365 %!assert (num2hex (intmax ("uint32")), "ffffffff")
366 %!assert (num2hex (intmax ("uint64")), "ffffffffffffffff")
367 
368 %!assert (hex2num (num2hex (pi)), pi)
369 %!assert (hex2num (num2hex (single (pi)), "single"), single (pi))
370 
371 %!error num2hex ()
372 %!error num2hex (1,2)
373 %!error num2hex (1,"foo")
374 %!error num2hex (1,2,3)
375 %!error num2hex (1j)
376 */
static void swap_bytes(void *ptr, unsigned int i, unsigned int j)
Definition: byte-swap.h:29
Definition: Cell.h:37
static void hex2num(const std::string &hex, void *num, size_t nbytes, bool swap_bytes)
Definition: hex2num.cc:63
OCTINTERP_API void print_usage(void)
Definition: defun.cc:54
identity matrix If supplied two scalar respectively For allows like xample val
Definition: data.cc:4986
for large enough k
Definition: lu.cc:617
const T * fortran_vec(void) const
Definition: Array.h:584
#define DEFUN(name, args_name, nargout_name, doc)
Macro to define a builtin function.
Definition: defun.h:53
void error(const char *fmt,...)
Definition: error.cc:578
const dim_vector & dims(void) const
Return a const-reference so that dims ()(i) works efficiently.
Definition: Array.h:442
static uint8_t hex2nibble(unsigned char ch)
Definition: hex2num.cc:45
float_format native_float_format(void)
Definition: mach-info.cc:62
octave_value retval
Definition: data.cc:6246
idx type
Definition: ov.cc:3114
void err_wrong_type_arg(const char *name, const char *s)
Definition: errwarn.cc:162
With real return the complex result
Definition: data.cc:3260
return octave_value(v1.char_array_value() . concat(v2.char_array_value(), ra_idx),((a1.is_sq_string()||a2.is_sq_string()) ? '\'' :'"'))
N Dimensional Array with copy-on-write semantics.
Definition: Array.h:125
p
Definition: lu.cc:138
args.length() nargin
Definition: file-io.cc:589
for i
Definition: data.cc:5264
octave_idx_type numel(void) const
Number of elements in the array.
Definition: Array.h:366
octave_idx_type length(void) const
If this string is the system will ring the terminal sometimes it is useful to be able to print the original representation of the string
Definition: utils.cc:888
bool words_little_endian(void)
Definition: mach-info.cc:76
static bool is_little_endian(bool is_float)
Definition: hex2num.cc:37