typecast in Matlab

c++, matlab

Solution

The value -0.0022 is being converted to two 16-bit values and that means your values are of type single (not double).

Let's try the other way around

>> typecast(uint16([65304 47886]), 'single')

ans =

   -0.0022

Now let's see the hexadecimal representation of these values look like:

>> format hex
>> uint16([65304 47886])

ans =

   ff18   bb0e

>> d=typecast(uint16([65304 47886]), 'single')

d =

   bb0eff18

Now you see that the first value, 65304, is the LSB 16-bit and 47886 is the 16-bit MSB. Therefore, your C++ implementation is correct. The reason that you do not get the correct values in C++ is that the value is not exactly equal to -0.0022. Since your environment is using the default `format` of `short` you do not see all significant digits. if you try this

>> format long e
>> typecast(uint16([65304 47886]), 'single')

ans =

  -2.1819528e-003

or in your environment just using

>> format long e
>> A(1)

You find the actual value in the array, and using it in your C++ code, should return the correct value.

Problem

I understood how typecast explained in the help file in the Matlab. But can't cope for my result. I tried to typecast a 3x4 matrix as follow. ``` A= -0.0022 -87.8788 -96.2848 -96.9586 0.9891 -52.9250 -52.7722 -52.7780 0.1473 -4.8680 -6.0184 -5.9894 ANS = typecast(A(:), 'uint16'); ``` Then ANS vector becomes ``` ANS=65304 47886 13518 16253 55853 15894 49650 49839 45875 49747 50835 49307 37329 49856 5820 49747 38546 49344 60110 49857 7340 49747 43369 49343 ``` That means -0.0022 have two 16 bits values of 65304 and 47886. How is it calculated? Then how can I implement in C++? In C++, I implemented like ``` float f = -0.0022; unsigned short a = static_cast<unsigned int>(f); unsigned short b = static_cast<unsigned int>(f)>>16; ``` I can't have a and b as 65304 and 47886.

Original source

Related problems