开发者

How to Variant's ChangeType to float if variant having INF or NAN values?

开发者 https://www.devze.com 2023-01-29 15:31 出处:网络
I am having float value in Variant, Initially this variant is a bstr type. I am using VariantChangeType to change to float type. and then I am getting float value from it and then i am converting into

I am having float value in Variant, Initially this variant is a bstr type. I am using VariantChangeType to change to float type. and then I am getting float value from it and then i am converting into byte vector format.

If variant has float values this works fine. If variant is having INF values, VariantChangeType gets failed. So i am getting 0 from variant.fltVal.

How to Changetype to float if variant having INF or NAN values? I want to get INF or NAN values in float.

Convert(_variant_t varVal,vector<byte> dataArr)
{
    HRESULT hr = VariantChangeType( varVal&, &varVal, 0 , VT_R4 ); 

   // Above code is failing if varVal.bstr contains 1.#INF" values 

    UINT size = 4;
    if ( data && dataItem.vt != VT_EMPTY )
    {
     float value = dataItem.fltVal;
     BYTE tmpBuf[4];
     me开发者_运维问答mcpy(tmpBuf, &value, sizeof(value));
     for( int i = size - 1 ; i >= 0 ; i-- )
     {    
         data->push_back(tmpBuf[i]);
     }    
     retVal = TRUE;
   }
}


in pseudo-language:

 if ( varVal.bstr.contains("1.#INF" ) ) {
   // assign plus infinity to your variant see http://stackoverflow.com/questions/2538339/infinity-in-msvc 
 } else if ( varVal.bstr.contains("-1.#INF" ) ) {
   // assign minus infinity to your variant see http://stackoverflow.com/questions/2538339/infinity-in-msvc 
 } else if ( varVal.bstr.contains("NaN" ) {
   // assign NaN to your variant see http://stackoverflow.com/questions/235386/using-nan-in-c
 } else {
   // your original working code for regular float values
 }

Please pay attention because it is a fragile solution: it relies on the string representations of infinity and NaN and maybe Microsoft can change them without warning.

This is an unofficial yet authoritative information by Raymond Chen: What does -1.#IND mean?: A survey of how the Visual C runtime library prints special floating point values, even if it is not related to VARIANT.

Output  Meaning
1#INF   Positive infinity
-1#INF  Negative infinity
1#SNAN  Positive signaling NaN
-1#SNAN Negative signaling NaN
1#QNAN  Positive quiet NaN
-1#QNAN Negative quiet NaN
1#IND   Positive indefinite NaN
-1#IND  Negative indefinite NaN

An official information is printf Type Field Characters.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号