HOWTO · Csharp
How to Convert Int to Byte in C#
Choose between converting an integer to one byte or serializing it as a byte array in C#.
On this page
In C#, the right conversion depends on what you need to store. A byte holds one unsigned value from 0 through 255. A byte[] holds the bytes that encode a larger value. Use Convert.ToByte when the result should be one byte; use BitConverter.GetBytes or a stream when you need the binary representation of an int. For a file or network format, also choose its required byte order explicitly.
Choose between a byte and a byte[]
An int is a signed 32-bit number, while a byte is one unsigned 8-bit number. Converting an int to byte therefore succeeds only when the value is between 0 and 255. A byte[], by contrast, can preserve all four bytes of an int; the order of those bytes determines how another system reconstructs the number.
Choose the scalar conversion for a value that is known to fit in one byte, such as a small count or channel value. Choose an array for serialization, binary protocols, or APIs that require bytes. Converting a number to its decimal text and encoding that text is a different operation: it stores characters such as 1, 2, and 3, not the binary representation of the integer 123.
Convert a value to a byte with Convert.ToByte
Convert.ToByte returns one scalar byte. The string overload parses decimal numeric text, while numeric overloads convert supported numeric types. For an integer variable, check that its value is within 0 through 255 before converting. An unchecked cast can discard higher bits instead of reporting an overflow.
Run this example:
using System;
class Program
{
static void Main()
{
string text = "42";
byte fromText = Convert.ToByte(text);
byte fromNumber = Convert.ToByte(90);
Console.WriteLine($"{fromText}, {fromNumber}");
}
}
42, 90
For string input, a null string converts to 0. Text that is not a number causes FormatException, while a parsed value outside 0 through 255 causes OverflowException.
The next example handles both failures and prints each caught exception type, so the two cases remain distinguishable. The FormatException comes from the nonnumeric text; the OverflowException comes from a parsed value above 255.
Run this failure-handling example:
using System;
class Program
{
static void Main()
{
string[] inputs = { "twelve", "300" };
foreach (string input in inputs)
{
try
{
byte value = Convert.ToByte(input);
Console.WriteLine($"{input} -> {value}");
}
catch (FormatException)
{
Console.WriteLine($"{input} -> FormatException");
}
catch (OverflowException)
{
Console.WriteLine($"{input} -> OverflowException");
}
}
}
}
The string-and-base overload, Convert.ToByte(value, fromBase), also returns one byte. It accepts bases 2, 8, 10, and 16; it does not accept every radix from 2 to 36. For example, Convert.ToByte("FF", 16) parses a hexadecimal value. Invalid digits or a value that does not fit the byte range cause a conversion error; a base outside the supported set causes ArgumentException. Do not describe this overload as converting an integer into a byte array.
Convert an int to a byte[] with BitConverter.GetBytes
BitConverter.GetBytes(int) returns four bytes containing the integer’s binary representation. Its byte order follows the current machine, which you can inspect with BitConverter.IsLittleEndian. The following complete example prints the bytes as decimal numbers and identifies the machine’s native byte order.
using System;
class Program
{
static void Main()
{
int value = 123456789;
byte[] bytes = BitConverter.GetBytes(value);
Console.WriteLine(string.Join(" ", bytes));
Console.WriteLine(BitConverter.IsLittleEndian ? "Little-endian" : "Big-endian");
}
}
This method is convenient when the receiving code uses the same byte-order convention. If the bytes are stored or sent to a different system, agree on the format rather than assuming both machines use the same order.
Write an int to a byte[] with BinaryWriter and MemoryStream
When code already writes a sequence of values to a stream, BinaryWriter can write the int and MemoryStream.ToArray() can return the accumulated bytes. BinaryWriter writes its primitive numeric values in little-endian order. Dispose the writer before reading the stream contents so its buffered work is complete; disposing the writer also disposes the stream, but ToArray() remains usable afterward.
using System;
using System.IO;
class Program
{
static void Main()
{
int value = 987654321;
byte[] bytes;
using (MemoryStream stream = new MemoryStream())
{
using (BinaryWriter writer = new BinaryWriter(stream))
{
writer.Write(value);
}
bytes = stream.ToArray();
}
Console.WriteLine(string.Join(" ", bytes));
}
}
This is useful when serializing several fields in order. The resulting array contains the stream’s full contents, not just the last integer written. If a protocol specifies another byte order, use the explicit order required by that protocol.
Control byte order when converting an int to a byte[]
Endianness determines whether the least significant or most significant byte comes first. BitConverter.GetBytes follows the machine’s native order, so reverse a copy only when native order differs from the format you need. The example below creates both little-endian and big-endian representations for the same value, independent of the machine’s native order.
using System;
class Program
{
static void Main()
{
int value = 567890123;
byte[] native = BitConverter.GetBytes(value);
byte[] littleEndian = (byte[])native.Clone();
byte[] bigEndian = (byte[])native.Clone();
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(littleEndian);
}
if (BitConverter.IsLittleEndian)
{
Array.Reverse(bigEndian);
}
Console.WriteLine("Little-endian: " + string.Join(" ", littleEndian));
Console.WriteLine("Big-endian: " + string.Join(" ", bigEndian));
}
}
Specify the required order at the boundary where bytes are written or read. Reversing a local array is appropriate for a fixed-width integer representation, but it does not define a complete serialization format: the format must also specify widths, signedness, and the order of multiple fields.