7017
|
1 ## Copyright (C) 2007 David Bateman |
6869
|
2 ## |
|
3 ## This file is part of Octave. |
|
4 ## |
|
5 ## Octave is free software; you can redistribute it and/or modify it |
|
6 ## under the terms of the GNU General Public License as published by |
7016
|
7 ## the Free Software Foundation; either version 3 of the License, or (at |
|
8 ## your option) any later version. |
6869
|
9 ## |
|
10 ## Octave is distributed in the hope that it will be useful, but |
|
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
13 ## General Public License for more details. |
|
14 ## |
|
15 ## You should have received a copy of the GNU General Public License |
7016
|
16 ## along with Octave; see the file COPYING. If not, see |
|
17 ## <http://www.gnu.org/licenses/>. |
6869
|
18 |
|
19 ## -*- texinfo -*- |
|
20 ## @deftypefn {Function File} {} swapbytes (@var{x}) |
|
21 ## Swaps the byte order on values, converting from little endian to big |
|
22 ## endian and visa-versa. For example |
|
23 ## |
|
24 ## @example |
|
25 ## @group |
|
26 ## swapbytes (uint16 (1:4)) |
|
27 ## @result{} [ 256 512 768 1024] |
|
28 ## @end group |
|
29 ## @end example |
|
30 ## |
|
31 ## @seealso{typecast, cast} |
|
32 ## @end deftypefn |
|
33 |
|
34 function y = swapbytes (x) |
|
35 if (nargin != 1) |
|
36 print_usage (); |
|
37 endif |
|
38 |
|
39 clx = class (x); |
|
40 if (strcmp (clx, "int8") || strcmp (clx, "uint8") || isempty (x)) |
|
41 y = x; |
|
42 else |
|
43 if (strcmp (clx, "int16") || strcmp (clx, "uint16")) |
|
44 nb = 2; |
|
45 elseif (strcmp (clx, "int32") || strcmp (clx, "uint32")) |
|
46 nb = 4; |
|
47 elseif (strcmp (clx, "int64") || strcmp (clx, "uint64") || |
|
48 strcmp (clx, "double")) |
|
49 nb = 8; |
|
50 else |
|
51 error ("swapbytes: invalid class of object"); |
|
52 endif |
|
53 y = reshape (typecast (reshape (typecast (x(:), "uint8"), nb, numel (x)) |
|
54 ([nb : -1 : 1], :) (:), clx), size(x)); |
|
55 endif |
|
56 endfunction |