Wednesday, December 19, 2012

C# PadLeft and PadRight

PadLeft/PadRight is padding on the left/Right with spaces or a specified Unicode character for a specified total length. Example as bellow:
 
string myString = "";
int myInt = 1;
myString = myInt.ToString().PadLeft(8, '0'); 
//myString will be 00000001 
myString = myInt.ToString().PadRight(8, '0');
//myString will be 10000000
MSDN Pad Left
MSDN Pad Right

C# Convert Ascii string to Hex string vice versa

Convert Ascii to Hex method
 
public string ConvertAsciiToHex(string asciiString)
{
    string hex = "";
    foreach (char c in asciiString)
    {
       int tmp = c;
       hex += String.Format("{0:X2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
    }
    return hex;
}
Convert Hex to Ascii method
 
public string ConvertHextoAscii(string HexString)
{
    string asciiString = "";
    for (int i = 0; i < HexString.Length; i += 2)
    {
       if (HexString.Length >= i + 2)
       {
          String hs = HexString.Substring(i, 2);
          asciiString = asciiString + System.Convert.ToChar(System.Convert.ToUInt32(HexString.Substring(i, 2), 16)).ToString();
       }
    }
    return asciiString;
}

C# Reverse String Method

Reverse String Method as below
 
public static string ReverseString(string s)
{        
    char[] charArray = s.ToCharArray();
    Array.Reverse(charArray);
    return new string(charArray);
}

C# Convert Decimal to Binary and Vice Versa

Decimal to Binary conversion as below:
 
int DecimalVal = 256;
string BinaryVal = Convert.ToString(DecimalVal, 2);
Binary to Decimal conversion as below:
 
string BinaryVal = "01001101";
string DecimalVal = Convert.ToInt32(BinaryVal, 2).ToString();

C# Custom Value from DateTimePicker

Custom value from datetimepicker as below:
 
string date = DateTimePicker1.Value.ToString("yyyy-MM-dd");

C# Convert Hex to Decimal and vice versa

Convert Hex to Decimal as below;
 
int DecimalVal = Convert.ToInt32(HexVal, 16);
Convert Decimal to Hex as below;
 
string HexVal = DecimalVal .ToString("X");

C# DateTime Custom String Method

Sample Code as bellow:
DateTime DT = DateTime.ParseExact("20121207015640","yyyyMMddHHmmss",null);  
For more info MSDN DateTime.ParseExact