33

I'm trying to do a hex calculation directly with bc, I already specified the scale.

echo 'scale=16;c06b1000-c06a5e78' | bc 

But I still get a zero. What could be wrong?

0

1 Answer 1

54
echo 'ibase=16;C06D1000-C06A5E78' | bc 176520 

Note that only UPPER CASE hex digits are supported as lower case ones would conflict with function and variable names, which is why you got 0 in your example (var1 - var2)

If you need the answer in hex too, just set the obase variable:

echo 'obase=16;ibase=16;C06D1000-C06A5E78' | bc 2B188 

PS: FYI scale isn't designed for conversion base. From man bc:

scale defines how some operations use digits after the decimal point. The default value of scale is 0. 
3
  • 1
    So the real answer on 'what could be wrong' is that bc only supports UPPER CASE for the hex digits, with credits to editor Stephane. Commented Jan 10, 2019 at 10:23
  • 10
    Note that it's important to set obase before you set ibase. If you set ibase first, then it affects the value parsed for obase too. ie ibase = 16; obase = 16; sets obase to 0x16 = 22 Commented Dec 10, 2019 at 1:41
  • one more important moment. bc does not understand small letters. thats why we need to convert small letters to capital letters manually. $ { echo -n "obase=16; ibase=16; " ; echo " aaaabbbccc + 121323 " | tr '[:lower:]' '[:upper:]'; } | bc Commented Dec 14, 2024 at 15:48

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.