changelog shortlog tags changeset files revisions annotate raw

scripts/general/bitset.m

changeset 10289: 4b124317dc38
parent:1bf0ce0930be
author: John W. Eaton <jwe@octave.org>
date: Tue Feb 09 20:58:55 2010 -0500 (61 minutes ago)
permissions: -rw-r--r--
description: base_properties::set_children: account for hidden children
1## Copyright (C) 2004, 2005, 2006, 2007, 2009 David Bateman
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
7## the Free Software Foundation; either version 3 of the License, or (at
8## your option) 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, see
17## <http://www.gnu.org/licenses/>.
18
19## -*- texinfo -*-
20## @deftypefn {Function File} {@var{x} =} bitset (@var{a}, @var{n})
21## @deftypefnx {Function File} {@var{x} =} bitset (@var{a}, @var{n}, @var{v})
22## Set or reset bit(s) @var{n} of unsigned integers in @var{a}.
23## @var{v} = 0 resets and @var{v} = 1 sets the bits.
24## The lowest significant bit is: @var{n} = 1
25##
26## @example
27## @group
28## dec2bin (bitset (10, 1))
29## @result{} 1011
30## @end group
31## @end example
32## @seealso{bitand, bitor, bitxor, bitget, bitcmp, bitshift, bitmax}
33## @end deftypefn
34
35## Liberally based of the version by Kai Habel from octave-forge
36
37function X = bitset (A, n, value)
38
39 if (nargin < 2 || nargin > 3)
40 print_usage ();
41 endif
42
43 if (nargin == 2)
44 value = 1;
45 endif
46
47 if (isa (A, "double"))
48 Bmax = bitmax;
49 Amax = log2 (Bmax) + 1;
50 _conv = @double;
51 else
52 if (isa (A, "uint8"))
53 Amax = 8;
54 _conv = @uint8;
55 elseif (isa (A, "uint16"))
56 Amax = 16;
57 _conv = @uint16;
58 elseif (isa (A, "uint32"))
59 Amax = 32;
60 _conv = @uint32;
61 elseif (isa (A, "uint64"))
62 Amax = 64;
63 _conv = @uint64;
64 elseif (isa (A, "int8"))
65 Amax = 8;
66 _conv = @int8;
67 elseif (isa (A, "int16"))
68 Amax = 16;
69 _conv = @int16;
70 elseif (isa (A, "int32"))
71 Amax = 32;
72 _conv = @int32;
73 elseif (isa (A, "int64"))
74 Amax = 64;
75 _conv = @int64;
76 else
77 error ("invalid class %s", class (A));
78 endif
79 Bmax = intmax (class (A));
80 endif
81
82 m = double (n(:));
83 if (any (m < 1) || any (m > Amax))
84 error ("n must be in the range [1,%d]", Amax);
85 endif
86
87 mask = bitshift (_conv (1), uint8 (n) - uint8 (1));
88 X = bitxor (A, bitand (A, mask));
89
90 if (value)
91 X = bitor (A, mask);
92 endif
93
94endfunction