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