2313
|
1 ## Copyright (C) 1996 Kurt Hornik |
2325
|
2 ## |
2313
|
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 |
|
7 ## the Free Software Foundation; either version 2, or (at your option) |
|
8 ## any later version. |
|
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 |
|
16 ## along with Octave; see the file COPYING. If not, write to the Free |
|
17 ## Software Foundation, 59 Temple Place - Suite 330, Boston, MA |
|
18 ## 02111-1307, USA. |
2268
|
19 |
2311
|
20 ## usage: dec2bin (x) |
|
21 ## |
|
22 ## Returns the binary number corresponding to the nonnegative integer |
|
23 ## x. For example, dec2bin (14) returns "1110". |
2268
|
24 |
2314
|
25 ## Author: jwe |
|
26 |
2311
|
27 function y = dec2bin (x) |
2268
|
28 |
2303
|
29 ## Original version by Kurt Hornik <Kurt.Hornik@ci.tuwien.ac.at>. |
2325
|
30 |
2268
|
31 if (nargin != 1) |
|
32 usage ("dec2bin (x)"); |
|
33 endif |
|
34 |
|
35 [nr, nc] = size (x); |
|
36 |
|
37 len = nr * nc; |
|
38 |
|
39 x = reshape (x, 1, len); |
|
40 |
|
41 eleo = empty_list_elements_ok; |
|
42 unwind_protect |
|
43 empty_list_elements_ok = 1; |
|
44 y = []; |
|
45 for i = 1:len |
|
46 tmp = x (i); |
|
47 if (tmp == round (tmp) && tmp >= 0) |
|
48 while (tmp >= 2) |
|
49 z = fix (tmp ./ 2); |
|
50 y = [y, tmp - 2 * z]; |
|
51 tmp = z; |
|
52 endwhile |
|
53 y = [y, tmp]; |
|
54 else |
|
55 error ("dec2hex: invalid conversion"); |
|
56 endif |
|
57 endfor |
|
58 y = fliplr (y); |
|
59 y = setstr (y + toascii ("0")); |
|
60 unwind_protect_cleanup |
|
61 empty_list_elements_ok = eleo; |
|
62 end_unwind_protect |
|
63 |
|
64 endfunction |