On Fri, Jan 14, 2011 at 8:11 PM, Benny Lofgren <[email protected]> wrote:
> + Makes it able to use C-style radix prefixes to integers in order to do
> calculations in octal and hexadecimal. In the olden days, early '80:s to be
> specific, I worked at a company that produced a unix flavour called D-NIX,
> which had this neat feature in its expr(1). It makes it a breeze to make
> quick radix conversions, for example. And I guess the habit stuck with me,
> for to this day it frustrates me not to be able to use expr for that. :-) I
> hope others find it useful too. For example:
>
>    skynet:/usr/src/bin/expr# expr 0x1ffff + 15
>    131086
>    skynet:/usr/src/bin/expr#
>
> - Hexadecimal numbers (starting with 0x or 0X) is no longer recognized as
> strings. (The common construct expr 'X'$FOO = 'X' would still work as
> expected, of course.) Probably not a big concern.
>
> - POSIX?

Unfortunately, this would make expr violate POSIX.  "0x0" must be
treated as a (non-empty) string and not as integer zero.  So, for
example:
  expr 0x0 '|' foo

must return '0x0' and
  expr 0x34

must return '0x34'.  Similarly:
  expr 030 '|' foo

must return '30'.


So, what's the answer for someone wanting to do base conversion?  If
they use sh/ksh, then the answer is $((...)):

$ echo $((0x20))
32
$

csh shmucks^Wusers can use bc or dc for arbitrary base conversion:

% printf 'ibase=16\n%s\n' 20 | bc
32
% echo 16i20p | dc
32
%

...or defer to sh:

% sh -c 'echo $((0x20))'
32
%


> +       /* In case there is only one operand, make sure it is validated
> +        * as an integer as well, in case we for example want to print it
> +        * in a different radix.
> +        */
> +       (void) to_integer(tokval);

Ahem:
$ obj/expr
Segmentation fault (core dumped)
$


Philip Guenther

Reply via email to