3

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.

bytecode77
  • 14,163
  • 30
  • 110
  • 141
batuman
  • 7,066
  • 26
  • 107
  • 229

1 Answers1

8

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.

Mohsen Nosratinia
  • 9,844
  • 1
  • 27
  • 52
  • But something is still missing. If I tried in C++ like float f = -8.7878799e+001; unsigned short a = static_cast(f); unsigned short b = static_cast(f)>>16;I got 65449 and 65535. Then I did typecast(uint16([65449 65535]), 'single'), I got NaN. – batuman Aug 19 '13 at 08:06
  • 3
    @batuman I think you need to use `reinterpret_cast` instead of `static_cast`. See this question http://stackoverflow.com/questions/1723575/how-to-perform-a-bitwise-operation-on-floating-point-numbers – Mohsen Nosratinia Aug 19 '13 at 08:17
  • Exactly. I did like float f = -8.7878799e+001; unsigned short a = *reinterpret_cast(&f); unsigned short b = *reinterpret_cast(&f)>>16; The result is same as in Matlab. – batuman Aug 19 '13 at 08:29