SuperMario
SuperMario

Reputation: 45

C# - how to do encoding on string or char?

I'm reading metadata from specific bytes in files but the results I get have no encoding. I would like to encode them to Encoding.Default for readability.

How do I convert either full Unicode string or at least a single char?

C# .NET 3.5

Upvotes: 2

Views: 2127

Answers (5)

Gregory A Beamer
Gregory A Beamer

Reputation: 17010

It will be something like this:

string s = Encoding.UTF8.GetString(bytesToGetStringFrom, 0, bytesToGetStringFrom.Length);

There are "encodings" other than UTF8.

Upvotes: 0

Shekhar_Pro
Shekhar_Pro

Reputation: 18430

use somthing like this

System.Text.Encoding.Default.GetChars(pass your byte array here)

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503050

You don't encode bytes to a particular encoding - you decode them from the original encoding. You have to use the right encoding to use - you can't just pick it arbitrarily.

Do these bytes actually represent text data? If so, what encoding do the already use? This should be part of the file format.

If they're not actually encoded text, but you want a reliable text representation of arbitrary binary data, use Convert.ToBase64String.

Upvotes: 4

Gabriel Magana
Gabriel Magana

Reputation: 4536

var myString = System.Text.Encoding.Unicode.GetString(myByteArray);

Would that work?

Upvotes: 2

Davide Piras
Davide Piras

Reputation: 44605

Have a look at the namespace System.Text.Encoding :)

Upvotes: 1

Related Questions