C# chars, bytes, and strings, Oh My.

Some simple code to show the conversions between the different data types:


// establish a base line
System.Console.WriteLine("Testing bytes, chars, encoding, etc.");
char myChar = 'a';
byte myCharBytes = Convert.ToByte(myChar);
System.Console.WriteLine("The number of bytes in a char is 1 byte.");
System.Console.WriteLine("The value of myCharBytes is " + myCharBytes);

// the following is wrong because it converts 97 to a string of "97"

string myByteString = myCharBytes.ToString();
System.Console.WriteLine("myByteString.Length = " + myByteString.Length);
System.Console.WriteLine("myByteString = " + myByteString);

// the following is correct because it converts 97 to "a"

char myGoodByteChar = Convert.ToChar(myCharBytes);
string myGoodByteCharString = Convert.ToString(myGoodByteChar);
System.Console.WriteLine("myGoodByteCharString = " + myGoodByteCharString);
System.Console.WriteLine("myGoodByteCharString contains " + Encoding.ASCII.GetByteCount(myGoodByteCharString) + " bytes.");




Comments

Popular posts from this blog

Using Reference Aliases

List of Visual Studio Keyboard Shortcuts

Quick Example of System.IO.Abstractions Use