Sunday 9 April 2017

Typecasting in Embedded C


"In this blog we will study about “Typecasting in Embedded  C”

Type casting in C language is the process of converting one data type variable to another data type. For example converting integer value to long integer value. These are also called short instruction in embedded C. Some time type casting is handled by the compiler and in some IDE’s programmer has to take care of this.   On the base of compiler capability types casting is of two types:
Implicit Type casting: in this Compiler will take care of all type casting functionality. 
Explicit Type casting: In this programmer has to take cares type casting when solving mathematical expressions. 
Syntax of typecasting is as follows:
(data_type)expression;
Here data_type is the new data type in to which we have to convert expression. Type casting also called short instruction in embedded C.

/**********************Example of type Casting************************/
unsigned char var1;     // declaration of unsigned character var1
float var2;                    // declaration of float variable var2
unsigned int var3;       //declaration of unsigned int variable var3

var1=40;                      // save value 40 to var1
var3= var1*10;           // if compiler does not support implicit type casting after this instruction                        //execution  var3 will contain 190. Because compiler consider var1 as char
var3 =  (unsigned int)  var1/10;  // after execution of this instruction var3 will contain 400.
var1= 55;
var2=(float)var1/6;  //in this case first we have type cast var1 to float and then divide by 6. 
                                   //In this case var2 will contain 9.166666
There are two type of type casting first is Upcasting and Downcasting. If we converting data type from lower data type to higher data type i.e. chats to integer or integer to float, then it is called Upcasting.  If we are converting from higher data type to lower data type, it is called Downcasting.
Down casting help when we have to convert 16 bit integer values to two bytes. Lower byte can be easily extracted without shifting operation.  For example:
var3 = 0x1234;
var1 = (unsigned char)var3;
in this case we type cast var3 to unsigned char.  After execution of this instruction var1 will contain 0x34.
Type casting is also used in arithmetic operation to get correct result. this is very much needed in case of division when integer gets divided and the remainder is omitted. In order to get correct value always use typecasting.