【问题标题】:typecast in MatlabMatlab中的类型转换
【发布时间】:2013-08-19 06:41:49
【问题描述】:

我了解在 Matlab 的帮助文件中如何解释类​​型转换。 但无法应付我的结果。我尝试按如下方式对 3x4 矩阵进行类型转换。

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

那么ANS向量就变成了

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

这意味着 -0.0022 有两个 16 位值 65304 和 47886。 它是如何计算的? 那我如何在 C++ 中实现呢? 在 C++ 中,我实现了类似

float f = -0.0022;
unsigned short a = static_cast<unsigned int>(f);
unsigned short b = static_cast<unsigned int>(f)>>16;

我不能将 a 和 b 作为 65304 和 47886。

【问题讨论】:

    标签: c++ matlab


    【解决方案1】:

    值 -0.0022 被转换为两个 16 位值,这意味着您的值是单(不是双)类型。

    我们换个方式试试

    >> typecast(uint16([65304 47886]), 'single')
    
    ans =
    
       -0.0022
    

    现在让我们看看这些值的十六进制表示形式如下:

    >> format hex
    >> uint16([65304 47886])
    
    ans =
    
       ff18   bb0e
    
    >> d=typecast(uint16([65304 47886]), 'single')
    
    d =
    
       bb0eff18
    

    现在您看到第一个值 65304 是 LSB 16 位,而 47886 是 16 位 MSB。因此,您的 C++ 实现是正确的。在 C++ 中没有得到正确值的原因是该值不完全等于 -0.0022。由于您的环境使用short 的默认format,因此您看不到所有有效数字。如果你试试这个

    >> format long e
    >> typecast(uint16([65304 47886]), 'single')
    
    ans =
    
      -2.1819528e-003
    

    或在您的环境中使用

    >> format long e
    >> A(1)
    

    您在数组中找到实际值,并在您的 C++ 代码中使用它,应该会返回正确的值。

    【讨论】:

    • 但是仍然缺少一些东西。如果我在 C++ 中尝试过 float f = -8.7878799e+001; unsigned short a = static_cast(f); unsigned short b = static_cast(f)>>16;我得到了 65449 和 65535。然后我做了 typecast(uint16([65449 65535]), 'single'),我得到了 NaN。
    • @batuman 我认为您需要使用reinterpret_cast 而不是static_cast。看到这个问题stackoverflow.com/questions/1723575/…
    • 没错。我确实喜欢 float f = -8.7878799e+001; unsigned short a = *reinterpret_cast(&f); unsigned short b = *reinterpret_cast(&f)>>16;结果与 Matlab 中的结果相同。
    猜你喜欢
    • 1970-01-01
    • 2011-02-03
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多