How to convert a string to fixed point format?

161 views Asked by At

I'm doing basic fixedpoint math in batch.

In batch there are only operations on integer mathematics and the internal format of the variables is 32 bit maximum.

I'm trying to implement Q16.16 by putting the number in just one variable. And if it's possible I also wanted to implement with 2 integer variable for large value.

EDIT 3:as written by Compo in the comments it would be a problem to do the multiplication in q16.16. So I will most likely reduce to Q15.15 but this is just a detail.

The first difficulty I find is loading the variables. Let's start from Q16.16.

I have to transform a real number, represented by a string because the batch does not support real numbers, and insert it into a variable which can then be used with integer mathematics.

Eg "1234.5678"

The first part is simple because I separate the integer part, insert it into the number and multiply by 65536 or do a shift <<16

setlocal EnableDelayedExpansion

set Num=1234.6789

For /F "Tokens=1-2 Delims=,." %%a in ("!Num!") Do (
Set Int=%%a
Set Fract=%%b
)

echo Num=!int!.!fract!

set /A "Num_Q=Int << 16"

echo Num_Q=!num_Q!

pause

The problem I have is converting the fractional part. How should I proceed?

Sorry if I framed the question incorrectly, but I am ready to correct it to meet the necessary requirements

EDIT: I wanted to address the problem exclusively in cmd, not powershell or vbscript, mshta or other.

EDIT 2: The final goal is to solve mathematical operations like: "sin(a * 0.123) * (13 + 5 / (.251 + pow(b * 4, 4))) - sin(b) * 55.25", but since I need a lot of speed I would like to use integer math as quickly as it is done in fixed point math. I have already developed 128bit multiplication operations Batch Math with cmd and also with Karatsuba. But they are very slow for my goal. Furthermore, the division is even slower. For division I am developing Knuth's method. But it's too slow and difficult. So I need a hand to overcome this little obstacle.

1

There are 1 answers

5
Stephan On

I would use the help of PowerShell to do the math, because it doesn't have the strict restrictions, cmd has (PowerShell supports floating-point natively), making your life much easier:

@echo off
setlocal

set "Num=2147483648.6789" & REM this is float and surely above INT32 range
call :calc %num% * 3
echo Result raw format:  %result%
REM in case you need a certain separator:
echo dot as separator:   %result:,=.%
echo comma as separator: %result:.=,%


goto :eof
:calc
For /F "Delims=" %%a in ('powershell %*') Do set "Result=%%a"
REM yes, that's all you need

Your batch variables stay STRING, without limitations on range or INT/Float