"grahamo" <gr************@hotmail.com> wrote in message
news:79*************************@posting.google.co m...
Hi,
i know I should use the new style casts and I intend to however I
would like to know how I go about this;
I have an unsigned char* that a 3rd party API returned to me. The API
reads text from a file and gives me that test as an unsigned char*.
For the sake of this example the text string is "100"
unsigned char* data = foo();
I need to get this into an unsigned int, which is what it ultimately
should be however I'm not sure of the best approach. I can cast it to
a char* and then use sprintf(result, "%d", arg) but I'm not sure if
thats the best approach.
What's the *correct* way to achieve it... in terms of code correctness
and "correct approach".
Thanks much for any info (as usual:)
There are many ways which are 'correct'. The 'best'
depends upon your needs. E.g.:
std::istringstream iss(static_cast<char>(foo()));
int i(0);
if(!(iss >> i))
std::cerr << "Cannot convert text to integer\n";
else
/* do your thing */
If I wanted more detailed control and error detection
for the conversion, I might do something like this:
std::string s(static_cast<char>(foo()));
long tmp(0);
tmp = strtol(s.c_str(), /* etc */ );
/* (look up 'strtol()' for the other */
/* parameters and how to use it) */
int i(0);
if(tmp >= std::numeric_limits<int>::min() &&
tmp <= std::numeric_limits<int>::max())
i = static_cast<int>(tmp);
else
std::cerr << "value out of range for int\n";
Also, if 'foo()'s return value can be NULL, you need to check for
that before using it.
-Mike