How to know the size of the string in bytes?

C#.NetStringSizeByte

C# Problem Overview


I'm wondering if I can know how long in bytes for a string in C#, anyone know?

C# Solutions


Solution 1 - C#

You can use encoding like ASCII to get a character per byte by using the System.Text.Encoding class.

or try this

  System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
  System.Text.ASCIIEncoding.ASCII.GetByteCount(string);

Solution 2 - C#

From MSDN:

>A String object is a sequential collection of System.Char objects that represent a string.

So you can use this:

var howManyBytes = yourString.Length * sizeof(Char);

Solution 3 - C#

System.Text.ASCIIEncoding.Unicode.GetByteCount(yourString);

Or

System.Text.ASCIIEncoding.ASCII.GetByteCount(yourString);

Solution 4 - C#

How many bytes a string will take depends on the encoding you choose (or is automatically chosen in the background without your knowledge). This sample code shows the difference:

void Main()
{
	string text = "a🡪";
	Console.WriteLine("{0,15} length: {1}", "String", text.Length);

	PrintInfo(text, Encoding.ASCII); // Note that '🡪' cannot be encoded in ASCII, information loss will occur
	PrintInfo(text, Encoding.UTF8); // This should always be your choice nowadays
	PrintInfo(text, Encoding.Unicode);
	PrintInfo(text, Encoding.UTF32);
}

void PrintInfo(string input, Encoding encoding)
{
	byte[] bytes = encoding.GetBytes(input);

	var info = new StringBuilder();
	info.AppendFormat("{0,16} bytes: {1} (", encoding.EncodingName, bytes.Length);
	info.AppendJoin(' ', bytes);
	info.Append(')');

	string decodedString = encoding.GetString(bytes);
	info.AppendFormat(", decoded string: \"{0}\"", decodedString);

	Console.WriteLine(info.ToString());
}

Output:

         String length: 3
        US-ASCII bytes: 3 (97 63 63), decoded string: "a??"
 Unicode (UTF-8) bytes: 5 (97 240 159 161 170), decoded string: "a🡪"
         Unicode bytes: 6 (97 0 62 216 106 220), decoded string: "a🡪"
Unicode (UTF-32) bytes: 8 (97 0 0 0 106 248 1 0), decoded string: "a🡪"

Solution 5 - C#

Starting with .Net5, you can use Convert.ToHexString. There's also a method for the reverse operation: Convert.FromHexString.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser705414View Question on Stackoverflow
Solution 1 - C#diyaView Answer on Stackoverflow
Solution 2 - C#MajidView Answer on Stackoverflow
Solution 3 - C#user596075View Answer on Stackoverflow
Solution 4 - C#Robert SynoradzkiView Answer on Stackoverflow
Solution 5 - C#SebastianView Answer on Stackoverflow