C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Main: The character representations from the input string were first converted to fit in one byte elements each.
Info: We see that the integer 68 corresponds to the uppercase letter "D". This is the standard.
Then: In the final loop, we examine each byte of the resulting byte array. We see its numeric and character-based representation.
ForeachByteC# program that uses Encoding.ASCII.GetBytes method
using System;
using System.Text;
class Program
{
static void Main()
{
// Input string.
const string input = "The Dev Codes";
// Invoke GetBytes method.
// ... You can store this array as a field!
byte[] array = Encoding.ASCII.GetBytes(input);
// Loop through contents of the array.
foreach (byte element in array)
{
Console.WriteLine("{0} = {1}", element, (char)element);
}
}
}
Output
68 = D
111 = o
116 = t
32 =
78 = N
101 = e
116 = t
32 =
80 = P
101 = e
114 = r
108 = l
115 = s
Tip: You will need to ensure System.Text is included to compile the program. Please add the using System.Text directive.
Note: We see that the byte array does not need to contain the "\0" character to be converted to a string correctly.
Space: The space character in the example is encoded as the byte 32. We provide more information on the char type.
CharC# program that converts byte array to string
using System;
using System.Text;
class Program
{
static void Main()
{
byte[] array =
{
68,
111,
116,
32,
78,
101,
116,
32,
80,
101,
114,
108,
115
};
string value = ASCIIEncoding.ASCII.GetString(array);
Console.WriteLine(value);
}
}
Output
The Dev Codes
Version 1: This code allocates an array of 10,000 strings. The memory this requires is measured.
Version 2: Here we change each string into a byte array. And the memory of this array is measured.
Byte ArrayResult: The string[] required about 480,000 bytes. The byte[][] (a jagged array of byte arrays) required 320,000 bytes.
Jagged ArraysTip: You can convert the byte arrays back into strings by calling ASCIIEncoding.ASCII.GetString.
C# program that changes string representation
using System;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
// Version 1: get string array.
long a = GC.GetTotalMemory(true);
string[] array = Get();
long b = GC.GetTotalMemory(true);
array[0] = null;
// Version 2: get byte arrays.
long c = GC.GetTotalMemory(true);
byte[][] array2 = Compress(Get());
long d = GC.GetTotalMemory(true);
array2[0] = null;
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
Console.WriteLine(d);
}
static string[] Get()
{
string[] output = new string[10000];
for (int i = 0; i < 10000; i++)
{
output[i] = Path.GetRandomFileName();
}
return output;
}
static byte[][] Compress(string[] array)
{
byte[][] output = new byte[array.Length][];
for (int i = 0; i < array.Length; i++)
{
output[i] = ASCIIEncoding.ASCII.GetBytes(array[i]);
}
return output;
}
}
Output
39128
479800
39784
320056