user3127017
user3127017

Reputation: 3

Sending chars from string to byte array C#

Which encoding should I use to write bbb to a file as exact bytes, so if the file were opened in a hex editor, its contents would be "99 59"?

The following methods created incorrect results, as listed:

Byte[] bbb = { 0x99, 0x59 };
string o = System.Text.Encoding.UTF32.GetString(bbb);

UTF32 (above) writes 'EF BF BD', UTF7 writes 'C2 99 59', UTF8 writes 'EF BF BD 59', Unicode writes 'E5 A6 99', ASCII writes '3F 59'

What encoding will produce the un-changed 8-bit bytes?

Upvotes: 0

Views: 160

Answers (1)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391336

If you want bytes to be written unencoded to a file/stream, simply write them to the file/stream.

File.WriteAllBytes(@"d:\temp\test.bin", bbb);

or

stream.Write(bbb, 0, bbb.Length);

Don't encode them at all.

Upvotes: 2

Related Questions