1 ## Copyright (C) 2004-2012 David Bateman
3 ## This file is part of Octave.
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 3 of the License, or (at
8 ## your option) any later version.
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.
15 ## You should have received a copy of the GNU General Public License
16 ## along with Octave; see the file COPYING. If not, see
17 ## <http://www.gnu.org/licenses/>.
20 ## @deftypefn {Function File} {@var{C} =} bitset (@var{A}, @var{n})
21 ## @deftypefnx {Function File} {@var{C} =} bitset (@var{A}, @var{n}, @var{val})
22 ## Set or reset bit(s) @var{n} of unsigned integers in @var{A}.
23 ## @var{val} = 0 resets and @var{val} = 1 sets the bits.
24 ## The lowest significant bit is: @var{n} = 1
28 ## dec2bin (bitset (10, 1))
32 ## @seealso{bitand, bitor, bitxor, bitget, bitcmp, bitshift, bitmax}
35 ## Liberally based on the version by Kai Habel from octave-forge
37 function C = bitset (A, n, val)
39 if (nargin < 2 || nargin > 3)
47 if (isa (A, "double"))
49 Amax = log2 (Bmax) + 1;
55 elseif (isa (A, "uint16"))
58 elseif (isa (A, "uint32"))
61 elseif (isa (A, "uint64"))
64 elseif (isa (A, "int8"))
67 elseif (isa (A, "int16"))
70 elseif (isa (A, "int32"))
73 elseif (isa (A, "int64"))
77 error ("bitset: invalid class %s", class (A));
79 Bmax = intmax (class (A));
83 if (any (m < 1) || any (m > Amax))
84 error ("bitset: N must be in the range [1,%d]", Amax);
87 mask = bitshift (_conv (1), uint8 (n) - uint8 (1));
88 C = bitxor (A, bitand (A, mask));
97 %!error bitset (1, 2, 3, 4);
100 %! assert (bitset ([0, 10], [3, 3]), [4, 14]);
103 %! for prec = [8, 16, 32, 64]
104 %! fcn = str2func (sprintf ("%sint%d", pfx{i}, prec));
105 %! assert (bitset (fcn ([0, 10]), [3, 3]), fcn ([4, 14]));
109 %!error bitset (0, 0);
110 %!error bitset (0, 55);
112 %!error bitset (int8 (0), 9);
113 %!error bitset (uint8 (0), 9);
115 %!error bitset (int16 (0), 17);
116 %!error bitset (uint16 (0), 17);
118 %!error bitset (int32 (0), 33);
119 %!error bitset (uint32 (0), 33);
121 %!error bitset (int64 (0), 65);
122 %!error bitset (uint64 (0), 65);