# HG changeset patch # User Rik # Date 1331941866 25200 # Node ID e995b1c97e13203544a50f10b1b956a7fa09fd3e # Parent 21ac4b576003cfee0d571d257a4c7f64bec408b0 Fix regression in bin2dec which did not allow space-separated input. * base2dec.m: Squeeze spaces from input before applying algorithm. * bin2dec.m: Add tests for using spaces in binary number. diff -r 21ac4b576003 -r e995b1c97e13 scripts/strings/base2dec.m --- a/scripts/strings/base2dec.m Thu Mar 15 13:03:27 2012 -0400 +++ b/scripts/strings/base2dec.m Fri Mar 16 16:51:06 2012 -0700 @@ -81,8 +81,27 @@ s = toupper (s); endif - ## Right justify the values before anything else. - s = strjust (s, "right"); + ## Right justify the values and squeeze out any spaces. + ## This looks complicated, but indexing solution is very fast + ## compared to alternatives which use cellstr or cellfun or looping. + [nr, nc] = size (s); + if (nc > 1) # Bug #35621 + s = s.'; + nonbl = s != " "; + num_nonbl = sum (nonbl); + nc = max (num_nonbl); + num_blank = nc - num_nonbl; + R = repmat ([1 2; 0 0], 1, nr); + R(2, 1:2:2*nr) = num_blank; + R(2, 2:2:2*nr) = num_nonbl; + idx = repelems ([false, true], R); + idx = reshape (idx, nc, nr); + + ## Create a blank matrix and position the nonblank characters. + s2 = repmat (" ", nc, nr); + s2(idx) = s(nonbl); + s = s2.'; + endif ## Lookup value of symbols in symbol table, with invalid symbols ## evaluating to NaN and space evaluating to 0. diff -r 21ac4b576003 -r e995b1c97e13 scripts/strings/bin2dec.m --- a/scripts/strings/bin2dec.m Thu Mar 15 13:03:27 2012 -0400 +++ b/scripts/strings/bin2dec.m Fri Mar 16 16:51:06 2012 -0700 @@ -28,6 +28,16 @@ ## @end group ## @end example ## +## Spaces are ignored during conversion and may be used to make the binary +## number more readable. +## +## @example +## @group +## bin2dec ("1000 0001") +## @result{} 129 +## @end group +## @end example +## ## If @var{s} is a string matrix, return a column vector with one converted ## number per row of @var{s}; Invalid rows evaluate to NaN@. ## @@ -54,6 +64,8 @@ %!assert(bin2dec ("1110"), 14); %!assert(bin2dec ("11111111111111111111111111111111111111111111111111111"), 2^53-1); %!assert(bin2dec ({"1110", "1111"}), [14; 15]); +%!assert (bin2dec ("1 0 1"), 5) +%!assert (bin2dec (char ("1 0 1", " 1111")), [5; 15]); %%Test input validation %!error bin2dec ();