-1

I want to convert a hexadecimal value to decimal value, perform some arithmetic operation and convert it back to hexadecimal. In an attempt to do so, I am facing the following error,

"myshell.sh: line 77: 16##0x00a002: invalid number (error token is "16##0x00a002")

The related line of code is:

SUBVER3_1=$((16##$SUBVER3_1))

Can someone let me know:

  1. What this error is and how can i fix it?
  2. How to perform arithmetic operations on hexadecimal numbers in shell?
チーズパン
  • 2,752
  • 8
  • 42
  • 63
Rjain
  • 127
  • 10
  • Possible duplicate of [Convert decimal to hexadecimal in UNIX shell script](http://stackoverflow.com/questions/378829/convert-decimal-to-hexadecimal-in-unix-shell-script) – Tom Fenech Jan 11 '16 at 10:34
  • 2
    Your script snippet is not valid `sh` -- you should probably tag it with one of `bash` (IMHO the most probable), `ksh`, or `zsh`. – tripleee Jan 11 '16 at 11:30

2 Answers2

4

The 0x prefix is not valid for base 16 notation. Strip it before converting. Also, if you are using Bash, the syntax for base conversion uses a single # after the base.

SUBVER3_1=$((16#${SUBVER3_1#0x}))

This uses the traditional POSIX ${variable#prefix} notation to strip off a prefix. The # in that is unrelated to the base#string notation.

The shell supports basic integer arithmetic. The arithmetic operations are independent of the base you are using; simple addition etc like $((255+255)) can use base-16 notation just as well $((16#FF+16#FF)) but keep in mind that division with only integers is of rather limited usefulness. If you want results in hex, printf can do that:

printf "%04x\n" $((16#ff + 16#ff))
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Is the `16##` a shell-specific feature, or something specified by POSIX? – Tom Fenech Jan 11 '16 at 11:06
  • 2
    It's not in POSIX, though I believe `ksh` and `zsh` support something similar, too. The OP uses Bash arithmetic evaluation syntax so that's what I'm guessing they are actually using. – tripleee Jan 11 '16 at 11:29
  • [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_04) does seem to indicate support for the `0x` prefix itself though. – Etan Reisner Jan 11 '16 at 12:24
0

The issue is now resolved, I used print statement to fix this issue instead of the above statement

SUBVER3_1=$(printf "%x" $SUBVER3_1) # Converting from decimal to hexadecimal

This served the purpose

Rjain
  • 127
  • 10