Tuesday, February 10, 2009

Byte, decimal, hex, string conversion in C#

1. string to byte array:

public static byte[] ToByteArray(string str)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}

2. byte to decimal
int ideciaml = (int)byteIn;

3. byte to char
char cChar = (char)byteIn;

4. byte to hex:
string sChar = string.Format("{0:x} ", byteIn);

5. All to string:

string sChar = (int)byteIn + "";
string sChar = (char)byteIn + "";
string sChar = string.Format("{0:x} ", byteIn);

6. Nonprintable to hex:

byte[] bReceived = ToByteArray(m_comm.ReadExisting());
foreach (byte bb in bReceived)
{
if((((int)bb)>32) && (((int)bb) <127))
txtData.Text += ((char)bb + "");
else
txtData.Text += ("0x" + string.Format("{0:x} ", bb));
}

No comments: