Wednesday, February 10, 2010

Type Casting in C#.net

TypeCasting:
Typecasting is the name given to transforming one type into another. There are two types of casting that can be performed on data types,
implicit and explicit

Implicit Typecast
Implicit casting is performed by the compiler when there is no possible loss of data. This is when a smaller data type is copied into a larger data type - e.g., converting a 16-bit short to a 32-bit integer value

Expilicit TypeCast:
Explicit casting requires the use of the cast operator (parentheses) when there is a possible loss of data
int fourBytes = 0x000000FE;
byte lowestByte = (byte)fourBytes;

int numericval=67;
byte bytevalue= (byte) numericvalue;

String to Byte Array Conversion in C# and VB.NET :

Convert string to byte Array in C#.net
public static byte[] StrToByteArray(string str){
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}

Converting Byte Array to String:
byte [] dBytes = ...
string str;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
str = enc.GetString(dBytes);


Convert Integer to Byte :
Use BitConverter to convert integer values to byte
byte[] numBytesBuf = new byte[4];
numBytesBuf =System.BitConverter.GetBytes(int32Input);

Convert bitarray to Int

BitConverter.ToInt32 Method
Returns a 32-bit signed integer converted from four bytes at a specified position in a byte array.

No comments:

Post a Comment