Click here to Skip to main content
15,888,316 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The problem that i m getting in this code is when i try to call WriteHeadAndBuffer(kwdId,sizeof(float),(unsigned char*)&f);
in the below code i am not getting correct value(Don't know what it is unicode or garbage) after type cast (unsigned char*)&f.

Is is possible to type cast float to unsigned char* like this...
I am using vs2008.



C
void CQ3DStreamFile::Write(const unsigned long kwdId,const char* keyword,float f)
{
    if (!CheckStream(kOpenedWrite))
        return;

    if (m_Binary)
    {
        WriteHeadAndBuffer(kwdId,sizeof(float),(unsigned char*)&f);
    }
    else
    {
        doWriteIndent();
        fprintf(m_File,"%s\t%s\n",keyword,STRFLOAT(f));
    }
}


[Modified: added code formatting]
Posted
Updated 12-Mar-10 10:10am
v2

If I am understanding your intent correctly, you are misunderstanding type casts and what they do. Your variable f contains a binary representation of a floating point number. You are then casting the address of that variable from float * to char *. This does nothing whatsoever to the contents of f. You now have a pointer that you have demanded that the compiler consider a pointer to char that points to nothing of the sort.

Evidently, what you want is a character representation of the value in f. You have no such thing in your code at present. Neither a C or a C++ cast operator is relevant to creating such a thing.

If I am misunderstanding what you are trying to do, please clarify your question.

There are a number of things around that can be used to do this. Some posibilites that you might look at: CString::Format()[^], sprintf()[^], boost::lexical_cast[^], and std::ostringstream which can be used similarly to std::cout. An article that discusses these is here[^].

Most of these work with chars and not unsigned chars, so you may need a cast from char * to unsigned char *. Also what CString will give you is a const char *.

Note: I have been assuming here that you are not using a unicode build and do not have to worry about conversions to/from a unicode encoding.
 
Share this answer
 
I guess, you want to perform a binary dump of a float,

but the writing does probably finish
at the first 0-byte of the floats content... :)

Could you post the implementation of WriteHeadAndBuffer(..) ?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900