2268
|
1 # Copyright (C) 1996 John W. Eaton |
|
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 the |
|
7 # Free Software Foundation; either version 2, or (at your option) any |
|
8 # later version. |
|
9 # |
|
10 # Octave is distributed in the hope that it will be useful, but WITHOUT |
|
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
12 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
13 # 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 02111-1307, USA. |
|
18 |
|
19 function y = dec2bin (x) |
|
20 |
|
21 # usage: dec2bin (x) |
|
22 # |
|
23 # Returns the binary number corresponding to the nonnegative integer |
|
24 # x. For example, dec2bin (14) returns "1110". |
|
25 |
|
26 # Original version by Kurt Hornik <Kurt.Hornik@ci.tuwien.ac.at>. |
|
27 |
|
28 if (nargin != 1) |
|
29 usage ("dec2bin (x)"); |
|
30 endif |
|
31 |
|
32 [nr, nc] = size (x); |
|
33 |
|
34 len = nr * nc; |
|
35 |
|
36 x = reshape (x, 1, len); |
|
37 |
|
38 eleo = empty_list_elements_ok; |
|
39 unwind_protect |
|
40 empty_list_elements_ok = 1; |
|
41 y = []; |
|
42 for i = 1:len |
|
43 tmp = x (i); |
|
44 if (tmp == round (tmp) && tmp >= 0) |
|
45 while (tmp >= 2) |
|
46 z = fix (tmp ./ 2); |
|
47 y = [y, tmp - 2 * z]; |
|
48 tmp = z; |
|
49 endwhile |
|
50 y = [y, tmp]; |
|
51 else |
|
52 error ("dec2hex: invalid conversion"); |
|
53 endif |
|
54 endfor |
|
55 y = fliplr (y); |
|
56 y = setstr (y + toascii ("0")); |
|
57 unwind_protect_cleanup |
|
58 empty_list_elements_ok = eleo; |
|
59 end_unwind_protect |
|
60 |
|
61 endfunction |
|
62 |