Matlab Double cast from Uint64

1.7k views Asked by At

I am casting a 64bit fixed point number to floating point. How should that be done in Matlab? The following code gives different results. What is the difference between typecast and the double(x)

temp = 2^32*uint64(MSB) + uint64(LSB);
out_0(1, 1) = typecast(temp, 'double');
out_1(1, 1) = double(temp);

An Example:

temp = 4618350711997530112

data = typecast(temp, 'double')

data =

    5.9194

>> double(temp)

ans =

    4.6184e+18
2

There are 2 answers

1
m7913d On BEST ANSWER

If you want to maintain the same number, you should definitely use double to convert it:

double Convert to double precision.
double(X) returns the double precision value for X.

Whereas typecast maintains the internal representation, i.e. the bytes are maintained the same but or differently interpreted:

typecast Convert datatypes without changing underlying data.
Y = typecast(X, DATATYPE) convert X to DATATYPE. If DATATYPE has
fewer bits than the class of X, Y will have more elements than X. If
DATATYPE has more bits than the class of X, Y will have fewer
elements than X.

Note that it is only possible to use typecast when the number of bytes are the same, which is not true for double as it tries to represent the same number as close as possible in double precision. For example, you cannot typecast uint32 to double, but you can typecast two uint32 to one double number. If you use double to convert it, you will obtain respectively one and two doubles.

C++ equivalent

X = double(uint64(123));
=> int64_t x = 123; double X = x;

X = typecast(uint64(123), 'double')
=> int64_t x = 123; double X = reinterpret_cast<double>(x);

0
Gelliant On

In addition, because it seems you have two 32-bit uint values MSB and LSB; To convert them to uint 64 you can use typecast.

U = typecast([MSB,LSB],'uint64')

Then conversion to double as suggested by m7913d

D = double(U)

So you see typecast has a very different function compared to double.