Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matlab Double cast from Uint64

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
like image 639
user1876942 Avatar asked Mar 08 '23 03:03

user1876942


1 Answers

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);

like image 152
m7913d Avatar answered Mar 11 '23 12:03

m7913d