-6

I'm working in an embedded environment which has python but not bc. I had a need to convert a hex number from stdin into a decimal value.

I have found a solution and I'm suspecting that others might also be interested in a solution for this simple task.

So lets say I want something like this:

$ echo "ff" | [something in python]
255 
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
ishahak
  • 6,585
  • 5
  • 38
  • 56
  • 2
    Honestly, this is just a trivial combination of "How do I take user input?", "How do I convert a hex string to a number?", and "How do I run a python command from the command line?". – Aran-Fey May 09 '18 at 11:27

1 Answers1

2

So here is a detailed answer:

  1. For reading the input, we can use python3's input() function.
  2. For converting a number from hex to int, we can use int() with 16 as its second parameter.
  3. For specifying a code to run in the command line, we use the -c option.

Putting all of this together, we are getting:

echo "ff" | python3 -c 'a=input();print(int(a,16))'
255
ishahak
  • 6,585
  • 5
  • 38
  • 56
  • You could directly use `print(int(input(),16))` (without the `a`) – Sruthi May 09 '18 at 11:26
  • 1
    You can just use bash directly instead of having to summon Python at all: https://stackoverflow.com/questions/13280131/hexadecimal-to-decimal-in-shell-script – Moses Koledoye May 09 '18 at 11:28