# HG changeset patch # User Rik # Date 1337211937 25200 # Node ID d4b4080faa47a70cd02b08373287e17055a46954 # Parent 6edd02858516436d4a6aed420b02ec040a635cd9 bitset.m: Update function to check for negative inputs. Update built-in tests. Use same variable names in documentation and in function. * bitset.m: Update function to check for negative inputs. Update built-in tests. Use same variable names in documentation and in function. diff -r 6edd02858516 -r d4b4080faa47 scripts/general/bitset.m --- a/scripts/general/bitset.m Wed May 16 16:56:35 2012 -0400 +++ b/scripts/general/bitset.m Wed May 16 16:45:37 2012 -0700 @@ -22,7 +22,7 @@ ## @deftypefnx {Function File} {@var{C} =} bitset (@var{A}, @var{n}, @var{val}) ## Set or reset bit(s) @var{n} of unsigned integers in @var{A}. ## @var{val} = 0 resets and @var{val} = 1 sets the bits. -## The lowest significant bit is: @var{n} = 1. All variables must be the +## The lowest significant bit is: @var{n} = 1. All variables must be the ## same size or scalars. ## ## @example @@ -34,14 +34,20 @@ ## @seealso{bitand, bitor, bitxor, bitget, bitcmp, bitshift, bitmax} ## @end deftypefn -function A = bitset (A, n, val) +function C = bitset (A, n, val) if (nargin < 2 || nargin > 3) print_usage (); endif + if (any (A(:) < 0)) + error ("bitset: A must be >= 0"); + endif + + sz = size (A); + if (nargin == 2) - val = true (size (A)); + val = true (sz); endif cl = class (A); @@ -51,8 +57,7 @@ Amax = log2 (Bmax); elseif (isinteger (A)) Bmax = intmax (cl); - ## FIXME: Better way to get number of bits than regexping? - Amax = str2num (nthargout (4, @regexp, cl, '\d{1,2}'){1}); + Amax = round (log2 (Bmax)); else error ("bitset: invalid class %s", cl); endif @@ -77,8 +82,9 @@ offmask = mask(off); endif - A(on) = bitor (A(on), onmask); - A(off) = bitand (A(off), bitcmp (offmask)); + C = zeros (sz, cl); + C(on) = bitor (A(on), onmask); + C(off) = bitand (A(off), bitcmp (offmask)); endfunction @@ -94,19 +100,23 @@ %! endfor ## Bug #36458 -%!assert (bitset(uint8 ([1, 2;3 4]), 1, [0 1; 0 1]), uint8 ([0, 3; 2 5])) - -%!error bitset (0, 0) -%!error bitset (0, 55) -%!error bitset (int8 (0), 9) -%!error bitset (uint8 (0), 9) -%!error bitset (int16 (0), 17) -%!error bitset (uint16 (0), 17) -%!error bitset (int32 (0), 33) -%!error bitset (uint32 (0), 33) -%!error bitset (int64 (0), 65) -%!error bitset (uint64 (0), 65) +%!assert (bitset (uint8 ([1, 2;3 4]), 1, [0 1; 0 1]), uint8 ([0, 3; 2 5])) %!error bitset (1) %!error bitset (1, 2, 3, 4) +%!error bitset (-1, 2) +%!error bitset ("1", 2) +%!error bitset (0, 0) +%!error bitset (0, 55) +%!error bitset (uint8 (0), 0) +%!error bitset (uint8 (0), 9) +%!error bitset (int8 (0), 9) +%!error bitset (int16 (0), 17) +%!error bitset (uint16 (0), 17) +%!error bitset (int32 (0), 33) +%!error bitset (uint32 (0), 33) +%!error bitset (int64 (0), 65) +%!error bitset (uint64 (0), 65) +%!error bitset (uint8 (1), [1 3]) +%!error bitset (uint8 (1:3), [1 3])