.NET
string conversion
byte array
C#
programming tips

How do you convert a string to a byte array in .NET?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Converting a string to a byte array in .NET is easy to write but easy to get wrong if the encoding is implicit. A string is Unicode text, while a byte array is raw binary data. The conversion between them depends entirely on the encoding you choose, so the safe pattern is to make that choice explicit and keep encode and decode behavior consistent.

Use an Explicit Encoding

The standard modern default is UTF-8.

csharp
1using System;
2using System.Text;
3
4string text = "Hello, café";
5byte[] bytes = Encoding.UTF8.GetBytes(text);
6
7Console.WriteLine(BitConverter.ToString(bytes));

If you later want the original string back, decode with the same encoding:

csharp
1using System;
2using System.Text;
3
4string text = "Hello, café";
5byte[] bytes = Encoding.UTF8.GetBytes(text);
6string roundTrip = Encoding.UTF8.GetString(bytes);
7
8Console.WriteLine(roundTrip);

The important rule is simple: encode and decode must agree.

Why Encoding Choice Matters

Different encodings produce different byte sequences for the same text. That is why "convert string to bytes" is not a cast. It is an encoding decision.

For example, UTF-8 and UTF-16 produce different output:

csharp
1using System;
2using System.Text;
3
4string text = "Aé";
5
6byte[] utf8 = Encoding.UTF8.GetBytes(text);
7byte[] utf16 = Encoding.Unicode.GetBytes(text);
8
9Console.WriteLine(BitConverter.ToString(utf8));
10Console.WriteLine(BitConverter.ToString(utf16));

If one system encodes with UTF-8 and another decodes with UTF-16, the recovered text will be wrong.

Round-Trip Test the Contract

Whenever text crosses a file, queue, or network boundary, add a round-trip test for the encoding you intend to use.

csharp
1using System;
2using System.Text;
3
4string[] samples =
5{
6    "plain-ascii",
7    "emoji 🚀",
8    "accent é",
9    "中文"
10};
11
12foreach (var sample in samples)
13{
14    byte[] data = Encoding.UTF8.GetBytes(sample);
15    string back = Encoding.UTF8.GetString(data);
16
17    if (!String.Equals(sample, back, StringComparison.Ordinal))
18    {
19        throw new Exception("Round trip failed");
20    }
21}
22
23Console.WriteLine("All round trips passed.");

This catches mismatches much earlier than an integration bug report.

Know When the Data Is Not Really Text

Not every byte array should come from a string. Many byte arrays represent binary payloads such as images, encrypted data, compressed content, or serialized objects.

If the payload is arbitrary binary and must pass through a text-only channel, use Base64 rather than pretending the bytes are text.

csharp
1using System;
2
3byte[] binary = { 0, 1, 2, 255, 128 };
4string base64 = Convert.ToBase64String(binary);
5byte[] restored = Convert.FromBase64String(base64);
6
7Console.WriteLine(base64);
8Console.WriteLine(restored.Length);

Base64 is a text-safe representation of binary data. It is not the same thing as choosing a text encoding for a string.

Optimize Only If It Is a Measured Hot Path

For most code, Encoding.UTF8.GetBytes is enough. If the conversion sits in a measured hot path, newer span-based APIs can reduce allocations.

csharp
1using System;
2using System.Text;
3
4string text = "high-throughput";
5Span<byte> buffer = stackalloc byte[64];
6int written = Encoding.UTF8.GetBytes(text.AsSpan(), buffer);
7
8Console.WriteLine(written);

This kind of optimization is useful for high-throughput services, but it adds complexity. Keep it for places where profiling shows that the allocation cost matters.

Centralize Encoding Rules

If bytes are written to files or sent across services, do not let encoding choices drift across the codebase. A good pattern is:

  • define the encoding once
  • use helper methods consistently
  • test against real samples from other systems

That reduces the chance that one component quietly switches to a different encoding and breaks interoperability.

Common Pitfalls

The biggest pitfall is using Encoding.Default, which makes behavior depend on platform or environment settings.

Another common issue is encoding with one codec and decoding with another. The code compiles fine, but the data contract is broken.

People also confuse text encoding with binary transport encoding and try to force arbitrary bytes through string conversions when Base64 is what they actually need.

Summary

  • Converting a string to bytes in .NET is an encoding choice, not a cast.
  • Use explicit UTF-8 in most modern applications unless you have a documented reason not to.
  • Decode with the same encoding you used to encode.
  • Use Base64 when binary data must travel through text-only channels.
  • Centralize encoding rules so file and service boundaries stay consistent.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.