4916
|
1 ## Copyright (C) 2004 David BAteman |
|
2 ## |
|
3 ## This program is free software; you can redistribute it and/or modify |
|
4 ## it under the terms of the GNU General Public License as published by |
|
5 ## the Free Software Foundation; either version 2 of the License, or |
|
6 ## (at your option) any later version. |
|
7 ## |
|
8 ## This program is distributed in the hope that it will be useful, |
|
9 ## but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
11 ## GNU General Public License for more details. |
|
12 ## |
|
13 ## You should have received a copy of the GNU General Public License |
|
14 ## along with this program; if not, write to the Free Software |
|
15 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
|
16 |
|
17 ## -*- texinfo -*- |
4920
|
18 ## @deftypefn {Function File} {@var{x} =} bitset (@var{a}, @var{n}) |
|
19 ## @deftypefnx {Function File} {@var{x} =} bitset (@var{a}, @var{n}, @var{v}) |
|
20 ## Set or reset bit(s) @var{n} of unsigned integers in @var{a}. |
4916
|
21 ## @var{v} = 0 resets and @var{v} = 1 sets the bits. |
|
22 ## The lowest significant bit is: @var{n} = 1 |
|
23 ## |
|
24 ## @example |
4920
|
25 ## dec2bin (bitset (10, 1)) |
4916
|
26 ## @result{} 1011 |
|
27 ## @end example |
|
28 ## |
4920
|
29 ## @seealso{bitand, bitor, bitxor, bitget, bitcmp, bitshift, bitmax} |
4916
|
30 ## @end deftypefn |
|
31 |
|
32 ## Liberally based of the version by Kai Habel from octave-forge |
|
33 |
|
34 function X = bitset (A, n, value) |
4920
|
35 |
4916
|
36 if (nargin < 2 || nargin > 3) |
|
37 usage ("bitset (A, n, v)"); |
|
38 endif |
|
39 |
|
40 if (nargin == 2) |
|
41 value = 1; |
|
42 endif |
|
43 |
4920
|
44 cname = class (A); |
4916
|
45 if (strcmp (cname, "double")) |
|
46 Bmax = bitmax; |
|
47 Amax = log2 (Bmax) + 1; |
4920
|
48 elseif strcmp("uint", substr (cname, 1, 4)) |
|
49 Bmax = intmax (cname); |
|
50 Amax = eval ([cname, " (log2 (double (intmax (cname))) + 1);"]); |
4916
|
51 else |
4920
|
52 Bmax = eval ([cname, " (-1);"]); |
|
53 Amax = eval ([cname, " (log2 (double (intmax (cname))) + 2);"]); |
4916
|
54 endif |
|
55 |
4920
|
56 Aone = eval ([ cname, "(1);"]); |
|
57 m = eval ([cname, " (n(:));"]); |
|
58 if (any (m < Aone) || any (m > Amax)) |
4916
|
59 error ("n must be in the range [1,%d]", Amax); |
|
60 endif |
|
61 |
|
62 ## XXX FIXME XXX Need extra cast to cname due to bad return value of .^ |
|
63 X = eval (["bitand (A, Bmax - ", cname, " (", cname, " (2) .^ (", cname, " (n) - Aone)));"]); |
|
64 |
|
65 if (value) |
|
66 X = eval (["bitor (A, ", cname, " (2) .^ (", cname, " (n) - Aone));"]); |
|
67 endif |
|
68 |
|
69 endfunction |