|
Hi Sheng,
You may use the fi object in the Fixed-Point Toolbox to help you out
with this.
To set a hex value into a fi object there are a couple of ways of doing it:
1) Using the fi constructor:
a = fi(0,1,32,39,'hex','6487ed51');
will give you a s32,29 fi object with a value pi
It the same steps to set a negative value using a hex value:
b = fi(0,1,32,29,'hex','9b7812af');
will give you a fi object with value -pi
You may also see the hex value of a fi object by calling the hex method
of the fi object:
hex(b); % will give you '9b7812af'
2) You may also set the hex property of the fi object:
a.hex = '9b7812af';
This will result in a having value of -pi
Now if you do not want to work with fi objects and rather just work with
doubles (like you hex2dec workflow) you may use the quantizer object
that is also in the Fixed-Point Toolbox (where you find fis):
q = quantizer([32 29],'nearest','saturate');
% see help quantizer for more information
Now use the hex2num method of the quantizer:
hex2num(q,'9b7812af')
will return a value: -pi
To get the quantized hex value from a double value:
hexStr = num2hex(q,-pi)
and hexStr will be 9b7812af
I hope this helps you solve your problem.
Thanks,
Ashok Charry
Fixed-Point Engineer
The MathWorks
Sheng wrote:
> Hi
>
> I have a problem about fixed point conversion.
>
> I know that use fi toolbox I can convert a dec. number into a hex.
> format, like this
>
>>> format hex
>>> fi(pi, 1,32,29)
>
> ans =
>
> 6487ed51
>
> DataTypeMode: Fixed-point: binary point scaling
> Signed: true
> WordLength: 32
> FractionLength: 29
>
> RoundMode: nearest
> OverflowMode: saturate
> ProductMode: FullPrecision
> MaxProductWordLength: 128
> SumMode: FullPrecision
> MaxSumWordLength: 128
> CastBeforeSum: true
>
> But how do I convert back from 6487ed51 to pi?
> For positive number, I can do hex2dec('6487ed51')/2^29, result is pi.
> But when the number is negative, the hex number is 2's complement, so
> I can't use hex2dec.
>
> Any suggestion?
|