Convert a hex number to decimal

2,389 views
Skip to first unread message

Bob Carroll

unread,
May 24, 2019, 3:25:06 PM5/24/19
to Ansible Project
This has to be easy, but I have tried a way to many things.  Given a hex number as a string, say '8d', I cannot convert it to a decimal string.
I presumed to prepend '0x' but '{{ "0x8d" | int }}' returns 0.  I am not having any better luck with jinja2 format().  I feel pretty stupid right now and I am tempted to just call the shell.
Sorry, but sometimes I really miss perl's weak type casting.

One of 100 attempts:

---
- hosts: localhost
  gather_facts: no
  tasks:
  - set_fact:
      hex_val: '0x8d'
  - set_fact:
      int_val: "{{ hex_val | int }}"
  - debug:
      var: int_val




flowerysong

unread,
May 24, 2019, 4:20:39 PM5/24/19
to Ansible Project

Bob Carroll

unread,
May 24, 2019, 5:15:56 PM5/24/19
to Ansible Project
Thanks so much for your reply.  Perhaps I need a bit more explanation.
When I try using this construct in a template, I get "do_int() got an unexpected keyword argument 'base'"

I get the same thing using a playbook:
---
- hosts: localhost
  gather_facts: no
  tasks:
  - set_fact:
      hex_val: '0x8d'
  - set_fact:
      int_val: "{{ hex_val | int(base=16) }}"
  - debug:
      var: int_val

TASK [set_fact] ****************************************************************
fatal: [localhost]: FAILED! => {"msg": "Unexpected templating type error occurred on ({{ hex_val | int(base=16) }}): do_int() got an unexpected keyword argument 'base'"}

Bob Carroll

unread,
May 24, 2019, 5:33:14 PM5/24/19
to Ansible Project
One more thing to note:
If the hex string is originally defined as an integer, the example playbook works as expected.  i.e. hex_val: 0x8d #without quotes
But since I am getting the "8d" from an external command, there does not seem to be a way to turn it back into an integer.

Kai Stian Olstad

unread,
May 24, 2019, 5:36:13 PM5/24/19
to ansible...@googlegroups.com
You are using a old Jinja, base was added to int in 2.8 that was released in 2015.
Current stable is 2.10.


--
Kai Stian Olstad

Bob Carroll

unread,
Jun 6, 2019, 4:23:20 PM6/6/19
to Ansible Project
Thanks for that.  I thought I was going crazy.  Unfortunately, as much as Red Hat is promoting Ansible, they are using really old back-end support libraries.  I did verify your solution with an updated python-jinja2 package.
Reply all
Reply to author
Forward
0 new messages