Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Numbers and Math

C# BinaryPrimitives class

Reference for System.Buffers.Binary.BinaryPrimitives: read and write integers and floats in big-endian or little-endian byte order from spans.

System.Buffers.Binary.BinaryPrimitives reads and writes numbers in a byte order that you choose, directly on spans of bytes. File formats and network protocols fix their byte order: TCP/IP headers, PNG and many others are big-endian ("network order"), while most CPUs you will meet are little-endian. BinaryPrimitives makes the order explicit, so your code behaves the same on every machine.

Every method has a BigEndian and a LittleEndian variant, plus Try... forms that return false instead of throwing when the span is too short. ReverseEndianness swaps the bytes of a value you already hold. You need using System.Buffers.Binary;.

C#
using System.Buffers.Binary;

byte[] buffer = new byte[4];
BinaryPrimitives.WriteInt32BigEndian(buffer, 258);   // 00 00 01 02

Try it

C# Writing and reading both orders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# A small binary header

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public static int    BinaryPrimitives.ReadInt32BigEndian(ReadOnlySpan<byte> source)
public static int    BinaryPrimitives.ReadInt32LittleEndian(ReadOnlySpan<byte> source)
public static void   BinaryPrimitives.WriteInt32BigEndian(Span<byte> destination, int value)
public static void   BinaryPrimitives.WriteInt32LittleEndian(Span<byte> destination, int value)
public static bool   BinaryPrimitives.TryReadInt32BigEndian(ReadOnlySpan<byte> source, out int value)
public static bool   BinaryPrimitives.TryWriteInt32BigEndian(Span<byte> destination, int value)
public static int    BinaryPrimitives.ReverseEndianness(int value)

The same set exists for short, ushort, int, uint, long, ulong, Int128, UInt128, Half, float and double. Single bytes need no byte order, so there is no byte version of ReverseEndianness that does anything useful.

Name Description
source The bytes to read from. Only the first N bytes are used (N is the size of the type).
destination The span to write into. Must be at least N bytes long.
value The number to write, or the number to byte-swap.

Returns: Read... returns the number. Write... returns nothing. TryRead.../TryWrite... return true on success. ReverseEndianness returns the value with its bytes in reverse order.

Errors: Read... and Write... throw ArgumentOutOfRangeException if the span is shorter than the type.

Usage notes

  • Pick the order from the format, not the machine. Do not call BitConverter and hope; BitConverter uses the machine's order, so its output changes between little- and big-endian systems. BinaryPrimitives does not.
  • Spans make slicing cheap. Use ranges like span[3..] to move through a buffer without copying. A byte[] converts to a span implicitly.
  • Try... for untrusted input. When the length comes from data you do not control, use the Try forms and check the result, or check span.Length yourself.
  • Signedness is just interpretation. Reading the same four bytes as uint or int differs only in how the top bit is read. Two's complement means no byte-order difference between the signed and unsigned versions.
  • Floating point. ReadDoubleBigEndian follows the IEEE 754 layout. It reads the bits and reinterprets them, so NaN payloads survive a round trip.
  • Not for variable-length formats. Varints (protobuf, LEB128) and text encodings need other code. BinaryReader and BinaryWriter read and write little-endian only, so use BinaryPrimitives for anything else.
  • ReverseEndianness cost. It compiles to a single byte-swap instruction on mainstream CPUs.