# Convert fractional number to hardware

Status
Not open for further replies.

#### stevepre

##### Member level 4 Is there any tools or anybody has a script or program that can quickly convert a fractional number to hardware representation?

For example: (simple one that people can usually calculate it by inspection)
0.5 = 0.1
0.25 = 0.01
-0.5 = 1.1
-0.25 = 1.11
-0.0001234 = ?????

And it gets more complicated if there is interger number combined, like 123.456

Is there a program or a script which can do that?
Thanks

#### jackson_peng

##### Full Member level 2 as for your criteria: the follow perl script can do the 16 bit fix point fractional number representation:
"-1<=x<1, the first bit is the signed bit, the remaining 15 bit are fraction part"

open SRC, "data";
while (<SRC>) {
chomp($_);$_=$_*(2**15); printf DST "%b,",$_;
}

#### stevepre

##### Member level 4 thanks Jackson_peng.

However, there's problem with your script when dealing with negative numbers. It always prints out full 32 chars....

Any solution?

#### nand_gates Checkout this just stripped off lower 16 bits from 32 bits
Code:
open SRC, "data";
while (<SRC>) {
chomp($_); print "n = ".$_." " ;
$_=$_*(2**15);
$t = sprintf( "%0.16b",$_);
@k = split(//,$t); for ($i=0; $i < 16;$i++) {
print $k[$i];
}
print "\n";
}

#### stevepre

##### Member level 4 Result:
n = 0.5 0100000000000000
n = 0.25 0010000000000000
n = 0.125 0001000000000000
n = 0.1234 0000111111001011
n = -0.5 1111111111111111
n = -0.25 1111111111111111
n = -0.125 1111111111111111
n = -0.1234 1111111111111111

still...negative number is still the main problem

#### jackson_peng

##### Full Member level 2 for negative number, just add (2**16) might remove the front 16 bit 1s

Status
Not open for further replies.