YoungMin Park
YoungMin Park

Reputation: 1189

C# Encoding.Default.GetBytes() method and Integer representation

I saw this code example:

using (FileStream fStream = File.Open(@"C:\myMessage.dat", FileMode.Create))
{
string msg = "Helloo";
byte[] msgAsByteArray = Encoding.Default.GetBytes(msg);

foreach (var a in msgAsByteArray)
{
    Console.WriteLine($"a: {a}");
}
// Write byte[] to file.
fStream.Write(msgAsByteArray, 0, msgAsByteArray.Length);

// Reset internal position of stream.
fStream.Position = 0;

// Read the types from file and display to console.
Console.Write("Your message as an array of bytes: ");
byte[] bytesFromFile = new byte[msgAsByteArray.Length];
for (int i = 0; i < msgAsByteArray.Length; i++)
{
    bytesFromFile[i] = (byte)fStream.ReadByte();
    Console.Write(bytesFromFile[i]);
}

// Display decoded messages.
Console.Write("\nDecoded Message: ");
Console.WriteLine(Encoding.Default.GetString(bytesFromFile));

And the result of Console.WriteLine($"a: {a}") is this:

a: 72
a: 101
a: 108
a: 108
a: 111
a: 111

1. I thought byte[] is composed of many each unit of byte. But each byte is represented in integer number. That numbers must be corresponding ASCII characters. In C#, byte array means data represented in ASCII?

2. Is the file myMessage.dat composed of binary data composed of only 0 and 1? But when I open myMessage.dat with the text editor, it's showing Helloo text string. What's the reason for this?

Upvotes: 1

Views: 3388

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51653

  1. A byte is a 8bit integer with values from 0 to 255. The output to console outputs the normal number, by providing a format string (https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings) you can output as hex. You can use this answer to get the binary representation.

You explicitly converted the "Halloo" to bytes with Encoding.Default.GetBytes() - that is kindof like converting it to its ascii value but heeding the default encoding on your system.

  1. Your texteditor interpretes the data of the file and displays it as it can. If you put a byte[] myBytes = new [] {0,7,12,3,9,30} into a file and open that with your textedit you will get nonreadable texts as "normal text" starts around 32 , before are f.e. tabs, bells, line feeds and other special non printable characters. See f.e. NonPrintableAscii

Upvotes: 2

Related Questions