# Decimal to float *SOLVED*

2 replies to this topic

### #1 Marten Troost

Marten Troost

GMC Member

• GMC Member
• 366 posts

Posted 14 February 2011 - 07:58 PM

Hi all,

I want to read and write data in binary files using the IEEE 754 standards for floating point numbers. The scripts for reading half, single and double precision floats are done and I am now working on the scripts for writing. This is where i am stuck. I started with the easiest one, a half precision float where the first bit should be the sign bit, 0 for positive and 1 for negative. The next five bits are the exponent and the last 10 bits are the fraction. I just don't know what mathematical steps i have to do to extract the exponent and convert the decimal value to a binary value. What I have so far:
```{
//Write half precision float
//argument0:    file
//argument1:    position
//argument2:    decimal

var s, i, f, e;

if sign(argument2) = -1
{
s   =   1;
}
else
{
s   =   0;
}

i   =   floor(abs(argument2));
f   =   frac(argument2);

file_bin_seek(argument0,argument1);
file_bin_write_byte(argument0,(s << 7) | (e << 2) | (f >>8));
file_bin_write_byte(argument0,f & 255);
}```

Edited by Marten Troost, 15 February 2011 - 05:20 PM.

• 0

### #2 Yourself

Yourself

The Ultimate Pronoun

• Retired Staff
• 7341 posts
• Version:Unknown

Posted 14 February 2011 - 08:19 PM

http://gmc.yoyogames...&st=0&p=1391333

I don't know if I ever made it properly handle denormal numbers.
• 0

### #3 Marten Troost

Marten Troost

GMC Member

• GMC Member
• 366 posts

Posted 15 February 2011 - 05:18 PM

Ah, thanks Yourself. I saw you script before but didn't understand it. Now I do. My complete script for writing a half precision float:
```{
var _n, _s, _e, _m, _i;
_n   =   argument2;

if _n < 0
{
_s    =   1;
_n   *=  -1;
}
else
{
_s   =   0;
}

_e   =   floor(log2(_n));

if _e <= -15
{
_n  =   _n / power(2,_e);
}
else
{
_n  =   _n / power(2,_e) - 1;
}

_e += 15;

_m   =   0;
_i   =   0;

while _i < 10
{
_n *= 2;
if _n >= 1
{
_n   -=  1;
_m   =   (_m << 1) + 1;
}
else
{
_m   =   _m << 1;
}

_i += 1;
}

file_bin_seek(argument0,argument1);
file_bin_write_byte(argument0,(_s << 7) | (_e << 2) | (_m >> 8));
file_bin_write_byte(argument0,_m & 255);
}```
argument0 being the file, argument1 the position and argument2 the value.
• 0

#### 0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users