Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Encoding ASCII into a Span<byte> buffer

Use Encoding.ASCII to encode a ReadOnlySpan<char> into a Span<byte> buffer. GetByteCount calculates the required size, while GetBytes writes the bytes and returns their count. Default replacement of non-ASCII text can lose data.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

using System;
using System.Text;

ReadOnlySpan<char> chars = "Hi";
Encoding encoding = Encoding.ASCII;
int required = encoding.GetByteCount(chars);
Span<byte> bytes = new byte[required];
int written = encoding.GetBytes(chars, bytes);

Encoding.ASCII in the System.Text namespace provides encoding for the 7-bit ASCII character set, covering U+0000–U+007F. It does not encode arbitrary Unicode text: its default fallback replaces unencodable text with ? (byte 0x3F). It therefore does not transliterate é to e and is not strict ASCII validation.

Encoding.GetByteCount(ReadOnlySpan<char>) calculates the exact byte count for the input and configured fallback without writing data. Encoding.GetBytes(ReadOnlySpan<char>, Span<byte>) performs the encoding into a caller-provided buffer and returns the number of bytes written. Unlike the GetBytes(string) overload, it does not return a new byte[].

The destination must have at least the calculated capacity; an undersized buffer causes ArgumentException. Calculate the size and encode using the same encoding and unchanged input. Pass only buffer[..written] onward, not the buffer's entire capacity. The example's fixed stackalloc buffer is sufficient for its short input; do not make an unbounded stack allocation depend on the size of external data.

The example uses span overloads available in .NET 10 and does not require preview syntax. Hi é produces four bytes, 48 69 20 3F, demonstrating the loss of é. If data loss is unacceptable, configure ASCII encoding with EncoderFallback.ExceptionFallback; if the format permits Unicode, choose an appropriate encoding such as Encoding.UTF8.

Examples

using System;
using System.Text;

ReadOnlySpan<char> text = "Hi \u00E9".AsSpan();
Encoding encoding = Encoding.ASCII;
int required = encoding.GetByteCount(text);
Span<byte> buffer = stackalloc byte[32];
int written = encoding.GetBytes(text, buffer);

Console.WriteLine($"Required: {required}; written: {written}");
Console.WriteLine(Convert.ToHexString(buffer[..written]));

Result

Required: 4; written: 4
4869203F

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources