ZetCode

C# byte

last modified October 4, 2026

This article explains the C# byte type and shows how to encode text, read and write files, and send byte data in an HTTP response.

The byte type is an unsigned 8-bit integral value type. It can store values from 0 through 255 and is commonly used for binary data, including file contents and network payloads. C# also provides the signed 8-bit sbyte type.

The code samples use top-level statements, available in C# 9 and later. They are intended for a .NET console project with implicit usings enabled.

The built-in 8-bit integral types are:

Keyword  Range         Representation        .NET type
sbyte    -128 to 127   Signed 8-bit integer   System.SByte
byte     0 to 255      Unsigned 8-bit integer System.Byte

byte and sbyte are C# aliases for System.Byte and System.SByte, respectively. Both use 8 bits; their ranges differ because one is unsigned and the other signed.

C# byte and sbyte

In the first example, we present the basic attributes of the byte types.

Program.cs
byte val1 = 5;
sbyte val2 = -4;

Console.WriteLine(val1);
Console.WriteLine(val2);

Console.WriteLine(val1.GetType());
Console.WriteLine(val2.GetType());

Console.WriteLine("------------------------");

Console.WriteLine(byte.MinValue);
Console.WriteLine(byte.MaxValue);

Console.WriteLine(sbyte.MinValue);
Console.WriteLine(sbyte.MaxValue);

Console.WriteLine("------------------------");

Console.WriteLine(typeof(byte));
Console.WriteLine(typeof(sbyte));
Console.WriteLine(default(byte));
Console.WriteLine(default(sbyte));

The program declares a byte and an sbyte, then prints their runtime types, ranges, and default values.

Console.WriteLine(val1.GetType());
Console.WriteLine(val2.GetType());

We can determine the type of a variable with GetType.

Console.WriteLine(byte.MinValue);
Console.WriteLine(byte.MaxValue);

The minimum and maximum values are available through the MinValue and MaxValue members.

Console.WriteLine(typeof(byte));
Console.WriteLine(typeof(sbyte));

The typeof operator returns a Type object for a type.

Console.WriteLine(default(byte));
Console.WriteLine(default(sbyte));

The default operator produces the default value of a type. For both 8-bit integer types, that value is zero.

$ dotnet run
5
-4
System.Byte
System.SByte
------------------------
0
255
-128
127
------------------------
System.Byte
System.SByte
System.Byte
0
0

C# byte arithmetic and overflow

Arithmetic with byte values produces an int. To store the result as a byte, convert it explicitly. A checked conversion throws if the value is outside the byte range; an unchecked conversion wraps the value.

Program.cs
byte first = 250;
byte second = 10;

int sum = first + second;
Console.WriteLine(sum);
Console.WriteLine(unchecked((byte)sum));

try
{
    Console.WriteLine(checked((byte)sum));
}
catch (OverflowException)
{
    Console.WriteLine("Overflow");
}
$ dotnet run
260
4
Overflow

The sum is an int, so it can hold 260. Converting 260 to byte in an unchecked context wraps it to 4; the checked conversion instead detects that 260 is greater than byte.MaxValue.

C# byte.TryParse

Use byte.TryParse to convert text when the input may be malformed or outside the range from 0 to 255. It returns false instead of throwing an exception when conversion fails.

Program.cs
foreach (string input in new[] { "200", "300" })
{
    if (byte.TryParse(input, out byte value))
    {
        Console.WriteLine(value);
    }
    else
    {
        Console.WriteLine($"{input} is not a byte value.");
    }
}
$ dotnet run
200
300 is not a byte value.

The first string represents a value in the byte range. The second represents 300, which cannot be stored in a byte, so TryParse returns false.

C# byte bit masks

Individual bits in a byte can represent flags. Assign each flag a distinct power of two, combine flags with the bitwise OR operator, and test a flag with the bitwise AND operator.

Program.cs
const byte Read = 1 << 0;
const byte Write = 1 << 1;
const byte Execute = 1 << 2;

byte permissions = Read | Write;
Console.WriteLine((permissions & Read) != 0);

permissions |= Execute;
Console.WriteLine(permissions);
$ dotnet run
True
7

The initial value combines the read and write bits. The AND expression checks whether the read bit is set; the compound OR assignment adds the execute bit, making the value 7.

C# convert string to bytes

We convert strings to bytes and vice versa with Encoding.

Program.cs
using System.Text;

string word = "čerešňa";

byte[] data = Encoding.UTF8.GetBytes(word);
Console.WriteLine(string.Join(" ", data));

string word2 = Encoding.UTF8.GetString(data);
Console.WriteLine(word2);

The string contains seven Unicode characters, including three letters that each require two bytes in UTF-8.

byte[] data = Encoding.UTF8.GetBytes(word);

To encode the string as UTF-8, we call Encoding.UTF8.GetBytes.

string word2 = Encoding.UTF8.GetString(data);

We decode the bytes with Encoding.UTF8.GetString. Use the same encoding when converting text to bytes and back.

$ dotnet run
196 141 101 114 101 197 161 197 136 97
čerešňa

The string has seven characters and encodes to ten bytes. Each of the three accented letters shown here uses two bytes in UTF-8.

C# write bytes to file

In the next example, we write some data to a text file.

public override void Write(byte[] buffer, int offset, int count);

The FileStream.Write method writes a block of bytes to a stream. Its parameters are the byte array, the zero-based offset in that array, and the number of bytes to write.

Program.cs
using System.Text;

var path = "words.txt";

using FileStream fs = File.Create(path);
byte[] data = Encoding.UTF8.GetBytes("falcon\nribbon\ncloud\nwater");
fs.Write(data, 0, data.Length);

Console.WriteLine("data written to file");

The example writes four words to a file.

using FileStream fs = File.Create(path);

We create or overwrite the file with File.Create, which returns a FileStream. The using declaration disposes the stream at the end of the scope.

byte[] data = Encoding.UTF8.GetBytes("falcon\nribbon\ncloud\nwater");

We encode the text as UTF-8 bytes with Encoding.UTF8.GetBytes.

fs.Write(data, 0, data.Length);

We write the entire byte array to the file stream with Write.

Get HTML page

The HttpClient.GetByteArrayAsync method sends a GET request and returns the successful response body as a byte array asynchronously.

Program.cs
string url = "https://example.com/";
using var client = new HttpClient();

byte[] data = await client.GetByteArrayAsync(url);

string fname = "index.html";
File.WriteAllBytes(fname, data);

We retrieve the page body as bytes with GetByteArrayAsync, then save it with File.WriteAllBytes. If index.html already exists, this call replaces it.

C# File.ReadAllBytes

The File.ReadAllBytes opens a binary file, reads the contents of the file into a byte array, and then closes the file.

Program.cs
var path = "favicon.ico";
byte[] data = File.ReadAllBytes(path);

int i = 0;

foreach (byte c in data)
{
    Console.Write("{0:X2} ", c);
    i++;

    if (i % 10 == 0)
    {
        Console.WriteLine();
    }
}

The example reads a binary file named favicon.ico from the current directory and prints its bytes in hexadecimal. The file must exist there, and the output depends on its contents.

$ dotnet run
00 00 01 00 01 00 10 10 00 00 
00 00 00 00 68 05 00 00 16 00 
00 00 28 00 00 00 10 00 00 00 
20 00 00 00 01 00 08 00 00 00 
00 00 00 01 00 00 00 00 00 00 
00 00 00 00 00 01 00 00 00 00 
00 00 00 00 00 00 FF FF FF 00 
4D 45 3D 00 00 00 00 00 00 00 
...

HttpServer example

An HTTP server writes response data to the response object's output stream.

Program.cs
using System.Net;
using System.Text;

using var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8001/");

listener.Start();

Console.WriteLine("Listening on port 8001...");

while (true)
{
    HttpListenerContext context = listener.GetContext();

    using HttpListenerResponse resp = context.Response;
    resp.ContentType = "text/plain; charset=utf-8";

    string data = "Hello there!";
    byte[] buffer = Encoding.UTF8.GetBytes(data);
    resp.ContentLength64 = buffer.Length;

    using Stream ros = resp.OutputStream;
    ros.Write(buffer, 0, buffer.Length);
}

The HttpListener class can create a basic HTTP listener. This example listens on localhost and sends a plain-text response.

using HttpListenerResponse resp = context.Response;
resp.ContentType = "text/plain; charset=utf-8";

The response's Content-Type identifies the body as UTF-8 plain text.

string data = "Hello there!";
byte[] buffer = Encoding.UTF8.GetBytes(data);

We transform the message into bytes.

resp.ContentLength64 = buffer.Length;

We set the response content length in bytes, as required by the HTTP response.

using Stream ros = resp.OutputStream;
ros.Write(buffer, 0, buffer.Length);

Finally, we write the bytes to the output stream with Write.

$ curl localhost:8001
Hello there!

Source

Byte struct - .NET API reference

In this article, we used C# byte types to encode text and work with file and HTTP data.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all C# tutorials.