-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathieee754.jinja
39 lines (39 loc) · 1.23 KB
/
ieee754.jinja
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
{% macro ieee754_float(hex_string) -%}
{% set h = hex_string.replace("fl_","").replace(" ","")|upper -%}
{# exit if the input is not hex -#}
{% if h|select('in','0123456789ABCDEF')|join() != h -%}
{{ None -}}
{% else -%}
{% set stds = {4:[5,10,15],8:[8,23,127],16:[11,52,1023]} -%}
{# exit if the input is the wrong length -#}
{% if h|length not in stds.keys() -%}
{{ None -}}
{% else -%}
{% set el, ml, b = stds[h|length] -%}
{% set d = h|int(base=16) -%}
{% set e = d|bitwise_and(('0'~'1'*el~'0'*ml)|int(base=2))//2**ml -%}
{# infinity or NaN -#}
{% if e == 2**el-1 -%}
{{ None -}}
{% else -%}
{% set s = d|bitwise_and(('1'~'0'*(el+ml))|int(base=2))//2**(el+ml) -%}
{% set m = d|bitwise_and(('1'*ml)|int(base=2))/2**ml -%}
{# subnormal -#}
{% if e == 0 -%}
{{ [1,-1][s]*m*2**-(b-1) -}}
{# normal -#}
{% else -%}
{{ [1,-1][s]*(1+m)*2**(e-b) -}}
{% endif -%}
{% endif -%}
{% endif -%}
{% endif -%}
{% endmacro -%}
{% macro float_ieee754_single(value) -%}
{% set dl = pack(value|float, "!f").decode('latin-1')|map('ord')|list -%}
{{ ("{:02x}"*dl|length).format(*dl) -}}
{% endmacro -%}
{% macro float_ieee754_double(value) -%}
{% set dl = pack(value|float, "!d").decode('latin-1')|map('ord')|list -%}
{{ ("{:02x}"*dl|length).format(*dl) -}}
{% endmacro -%}