Converting char array to double in C?

I want to add an integer value to an unsigned char array. and I want the result back in form of unsigned char array. How can I do it?

  • Language of implementation is C. Should I first typecast unsigned char array into int and add the integer value? And then again typecast the result back to unsigned char array. But type casting int into char can result in wrong value.

  • Answer:

    The reason you might get an invalid value is overflow. If you need to do this and be sure you get the correct results, you need to check that there's no overflow. But then you are left with the problem that if there would be, then what? More specifically, typically an unsigned char is 8 bits while an unsigned int is 32 bits. So int can hold a much bigger value than char. An 8-bit char can hold values between 0 and 255. If that int holds value 256 and char is 0 and you add these two and cast to char, char can't hold that value and an overflow occurs. The C standard doesn't even say what the result should be in that case so the result is undefined (depends on the compiler). Of course this holds true even if you add a char and a char and try to store the result in a char (what would happen if the values were 255 and 255?). What you should do, if you really insist on using a char array, is to add the two numbers to a variable that can store a big enough value and then manually check if the result fits into a char. If not, then you need to do some error handling. What that is depends on your application. http://en.wikipedia.org/wiki/Integer_overflow http://www.fefe.de/intof.html (this explains how to deal with overflows) * Note, I speak of "int" and "char" here, in this case I assume unsigned's even though I don't specify it every time.

Marko Poutiainen at Quora Visit the source

Was this solution helpful to you?

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.