A comprehensive set of utilities for working with byte arrays in .NET applications. These helpers are designed for performance, safety, and ease of use across all supported platforms.
- ByteArrayBuilder: Fluently build byte arrays from various types and encodings
- ByteArrayExtensions: Extension methods for reading primitives, strings, and complex types from byte arrays
- DateTime & Time Operations: Convert DateTime, TimeSpan, DateTimeOffset, and Unix timestamps
- Network & Protocol Support: IP addresses, endpoints, big-endian conversions, and TLV protocol parsing
- Async Operations: File I/O, parallel processing, and cryptographic operations with cancellation support
- Compression: GZip, Deflate, and Brotli compression/decompression
- GUID Operations: Convert between GUIDs and byte arrays with multiple format options
- Utilities & Analysis: Binary string representation, entropy calculation, and performance measurement
- Array Manipulation: Safe operations like slicing, concatenation, trimming, reversing, and XOR
- Pattern Matching: Search and compare byte arrays with StartsWith, EndsWith, IndexOf, and equality checks
- Format Conversion: Convert to/from hex strings, Base64, ASCII, and UTF-8 encodings
- Object Serialization: Convert objects and primitives to byte arrays with type safety
- Safe Operations: OrDefault methods that never throw exceptions and bounds-checked operations
The following table shows all types that can be converted from byte arrays, with support across byte[], ReadOnlySpan<byte>, and ReadOnlyMemory<byte>:
| Type | Size (bytes) | byte[] | ReadOnlySpan<byte> | ReadOnlyMemory<byte> | Notes |
|---|---|---|---|---|---|
bool | 1 | ✅ | ✅ | ➡️ | True[1] or False[0] |
byte | 1 | ✅ | ✅ | ➡️ | Unsigned 8-bit (0-255) |
sbyte | 1 | ✅ | ✅ | ➡️ | Signed 8-bit (-128 to 127) |
char | 2 | ✅ | ✅ | ➡️ | Unicode character |
short | 2 | ✅ | ✅ | ➡️ | Signed 16-bit (-32,768 to 32,767) |
ushort | 2 | ✅ | ✅ | ➡️ | Unsigned 16-bit (0 to 65,535) |
int | 4 | ✅ | ✅ | ➡️ | Signed 32-bit |
uint | 4 | ✅ | ✅ | ➡️ | Unsigned 32-bit |
long | 8 | ✅ | ✅ | ➡️ | Signed 64-bit |
ulong | 8 | ✅ | ✅ | ➡️ | Unsigned 64-bit |
float | 4 | ✅ | ✅ | ➡️ | Single-precision |
double | 8 | ✅ | ✅ | ➡️ | Double-precision |
Half | 2 | ✅ | ✅ | ➡️ | Half-precision |
decimal | 16 | ✅ | ✅ | ➡️ | High-precision decimal |
DateTime | 8 | ✅ | ✅ | ➡️ | Binary representation |
TimeSpan | 8 | ✅ | ✅ | ➡️ | Ticks representation |
DateTimeOffset | 16/10 | ✅ | ✅ | ➡️ | DateTime + offset |
Guid | 16 | ✅ | ✅ | ➡️ | UUID/GUID |
string (UTF-8) | Variable | ✅ | ✅ | ➡️ | UTF-8 encoded |
string (ASCII) | Variable | ✅ | ✅ | ➡️ | ASCII encoded |
string (Unicode) | Variable | ✅ | ❌ | ➡️ | Unicode encoded |
string (Hex) | Variable | ✅ | ✅ | ➡️ | Hexadecimal representation |
string (Base64) | Variable | ✅ | ✅ | ➡️ | Base64 encoded |
IPAddress (IPv4) | 4 | ✅ | ✅ | ➡️ | IPv4 address |
IPAddress (IPv6) | 16 | ✅ | ✅ | ➡️ | IPv6 address |
IPEndPoint (IPv4) | 6 | ✅ | ❌ | ➡️ | IPv4 address + port |
IPEndPoint (IPv6) | 18 | ✅ | ❌ | ➡️ | IPv6 address + port |
short (Big-endian) | 2 | ✅ | ❌ | ➡️ | Network byte order |
ushort (Big-endian) | 2 | ✅ | ✅ | ➡️ | Network byte order |
int (Big-endian) | 4 | ✅ | ❌ | ➡️ | Network byte order |
uint (Big-endian) | 4 | ✅ | ✅ | ➡️ | Network byte order |
long (Big-endian) | 8 | ✅ | ❌ | ➡️ | Network byte order |
ulong (Big-endian) | 8 | ✅ | ✅ | ➡️ | Network byte order |
Enum<T> | 4 | ✅ | ✅ | ➡️ | Any enum type |
Version | 16 | ✅ | ✅ | ➡️ | .NET Version object |
DateTime (Unix) | 4 | ✅ | ✅ | ➡️ | Seconds since epoch |
- ✅ Fully Supported - All conversion methods available
- ❌ Not Available - Type conversion not implemented
- ➡️ Via Span -
ReadOnlyMemory<byte>uses.Spanproperty to accessReadOnlySpan<byte>methods
- Standard:
ToType(ref position)andToType(position)- Throws on error - Safe:
ToTypeOrDefault(ref position, defaultValue)andToTypeOrDefault(position, defaultValue)- Returns default on error
- Position Tracking:
ref int positionparameter automatically advances - Bounds Checking: All methods validate array/span boundaries
- Endianness Support: Network byte order conversions for multi-byte integers
- String Length Handling: Automatic and manual length specification for strings
- Unix Timestamps: Convert POSIX timestamps to DateTime
usingPlugin.ByteArrays;usingvarbuilder=newByteArrayBuilder();builder.Append(0x01).AppendUtf8String("Hello").Append(newbyte[]{0x02,0x03}).Append(42).AppendHexString("DEADBEEF");byte[]result=builder.ToByteArray();usingPlugin.ByteArrays;byte[]data={0x01,0x00,0x48,0x65,0x6C,0x6C,0x6F};varposition=0;boolflag=data.ToBoolean(refposition);// reads 1 byteintvalue=data.ToInt32(refposition);// reads 4 bytes, advances positionstringtext=data.ToUtf8String(refposition,5);// reads 5 bytes// Safe variants that don't throwvarsafeValue=data.ToInt16OrDefault(refposition,defaultValue:-1);usingPlugin.ByteArrays;byte[]data={0x10,0x20,0x30,0x40,0x00,0x00};// Safe slicingbyte[]slice=data.SafeSlice(1,3);// [0x20, 0x30, 0x40]// Concatenationbyte[]a={0x01,0x02};byte[]b={0x03,0x04};byte[]combined=ByteArrayExtensions.Concatenate(a,b);// [0x01, 0x02, 0x03, 0x04]// Trimming trailing zerosbyte[]trimmed=data.TrimEndNonDestructive();// [0x10, 0x20, 0x30, 0x40]// Reverse and XOR operationsbyte[]reversed=data.Reverse();byte[]xorResult=a.Xor(newbyte[]{0xFF,0xFF});usingPlugin.ByteArrays;byte[]data={0x48,0x65,0x6C,0x6C,0x6F};byte[]pattern={0x65,0x6C};boolstarts=data.StartsWith(newbyte[]{0x48,0x65});// trueboolends=data.EndsWith(newbyte[]{0x6C,0x6F});// trueintindex=data.IndexOf(pattern);// 1// Array comparisonbyte[]other={0x48,0x65,0x6C,0x6C,0x6F};boolidentical=data.IsIdenticalTo(other);// trueusingPlugin.ByteArrays;// String to byte arraybyte[]utf8Bytes="Hello World".Utf8StringToByteArray();byte[]asciiBytes="Hello".AsciiStringToByteArray();byte[]hexBytes="48656C6C6F".HexStringToByteArray();// "Hello" in hexbyte[]base64Bytes="SGVsbG8=".Base64StringToByteArray();// "Hello" in base64// Byte array to stringstringhex=data.ToHexString("-","0x");// "0x48-0x65-0x6C-0x6C-0x6F"stringbase64=data.ToBase64String();stringutf8=data.ToUtf8String(refposition,length:5);usingPlugin.ByteArrays;// DateTime conversionsvarnow=DateTime.Now;byte[]dateTimeBytes=BitConverter.GetBytes(now.ToBinary());varposition=0;DateTimerestored=dateTimeBytes.ToDateTime(refposition);// Unix timestamp supportintunixTimestamp=1672502400;// 2023-01-01 00:00:00 UTCbyte[]timestampBytes=BitConverter.GetBytes(unixTimestamp);position=0;DateTimefromUnix=timestampBytes.ToDateTimeFromUnixTimestamp(refposition);// TimeSpan operationsvartimeSpan=newTimeSpan(1,2,3,4,5);byte[]spanBytes=BitConverter.GetBytes(timeSpan.Ticks);position=0;TimeSpanrestoredSpan=spanBytes.ToTimeSpan(refposition);// DateTimeOffset with timezonevaroffset=newDateTimeOffset(2023,6,15,14,30,0,TimeSpan.FromHours(-8));// Complex serialization combining DateTime and TimeSpanusingPlugin.ByteArrays;usingSystem.Net;// IP Address conversionsvaripv4=IPAddress.Parse("192.168.1.1");byte[]ipBytes=ipv4.GetAddressBytes();position=0;IPAddressrestored=ipBytes.ToIPAddress(refposition);// IPv6 supportvaripv6=IPAddress.Parse("2001:db8::1");byte[]ipv6Bytes=ipv6.GetAddressBytes();position=0;IPAddressrestoredV6=ipv6Bytes.ToIPAddress(refposition,isIPv6:true);// Network endpointsvarendpoint=newIPEndPoint(ipv4,8080);// Serialize endpoint with network byte order (big-endian)varendpointBytes=ipv4.GetAddressBytes().Concat(BitConverter.GetBytes((ushort)8080).Reverse()).ToArray();position=0;varrestoredEndpoint=endpointBytes.ToIPEndPoint(refposition);// Big-endian numeric conversions for network protocolsbyte[]networkData={0x12,0x34,0x56,0x78};position=0;intnetworkInt=networkData.ToInt32BigEndian(refposition);// 0x12345678// TLV (Type-Length-Value) protocol parsingbyte[]tlvData={0x01,0x00,0x05,0x48,0x65,0x6C,0x6C,0x6F};// Type=1, Length=5, Value="Hello"position=0;vartlvRecord=tlvData.ParseTlv(refposition);Console.WriteLine($"Type: {tlvRecord.Type}, Value: {Encoding.UTF8.GetString(tlvRecord.Value)}");usingPlugin.ByteArrays;// Async file operationsbyte[]data={0x01,0x02,0x03,0x04};awaitdata.WriteToFileAsync("output.bin");byte[]fileData=awaitByteArrayAsyncExtensions.ReadFromFileAsync("input.bin");// Parallel processing with cancellationvarsource=newCancellationTokenSource(TimeSpan.FromSeconds(30));byte[][]chunks={data1,data2,data3,data4};varresults=awaitchunks.ProcessInParallelAsync(async(chunk,ct)=>{// Process each chunk asynchronouslyreturnawaitSomeAsyncOperation(chunk,ct);},maxDegreeOfParallelism:4,cancellationToken:source.Token);// Cryptographic operationsbyte[]hash=awaitdata.ComputeSha256Async();byte[]randomBytes=awaitByteArrayAsyncExtensions.GenerateRandomBytesAsync(32);usingPlugin.ByteArrays;byte[]originalData="This is some data to compress".Utf8StringToByteArray();// GZip compressionbyte[]gzipCompressed=originalData.CompressGZip();byte[]gzipDecompressed=gzipCompressed.DecompressGZip();// Deflate compressionbyte[]deflateCompressed=originalData.CompressDeflate();byte[]deflateDecompressed=deflateCompressed.DecompressDeflate();// Brotli compression (best compression ratio)byte[]brotliCompressed=originalData.CompressBrotli();byte[]brotliDecompressed=brotliCompressed.DecompressBrotli();// Compare compression ratiosConsole.WriteLine($"Original: {originalData.Length} bytes");Console.WriteLine($"GZip: {gzipCompressed.Length} bytes ({(double)gzipCompressed.Length/originalData.Length:P1})");Console.WriteLine($"Brotli: {brotliCompressed.Length} bytes ({(double)brotliCompressed.Length/originalData.Length:P1})");usingPlugin.ByteArrays;// GUID conversionsvarguid=Guid.NewGuid();byte[]guidBytes=guid.ToByteArray();position=0;Guidrestored=guidBytes.ToGuid(refposition);// Safe GUID operationsGuidsafeGuid=invalidData.ToGuidOrDefault(refposition,Guid.Empty);usingPlugin.ByteArrays;byte[]data={0xAA,0xBB,0xCC,0xDD};// Binary representationstringbinary=data.ToBinaryString();// "10101010 10111011 11001100 11011101"// Statistical analysisdoubleentropy=data.CalculateEntropy();varstats=data.AnalyzeDistribution();Console.WriteLine($"Entropy: {entropy:F3}, Most frequent byte: 0x{stats.MostFrequentByte:X2}");// Performance measurementvarstopwatch=data.StartPerformanceMeasurement();// ... do some operations ...varelapsed=data.StopPerformanceMeasurement(stopwatch);Console.WriteLine($"Operation took: {elapsed.TotalMilliseconds:F2}ms");// Memory usage analysislongmemoryUsage=data.EstimateMemoryUsage();Console.WriteLine($"Estimated memory usage: {memoryUsage} bytes");usingPlugin.ByteArrays;// Convert any supported type to byte arrayintnumber=42;byte[]numberBytes=number.ToByteArray();DateTimenow=DateTime.Now;byte[]dateBytes=now.ToByteArray();// Enums are supportedMyEnumenumValue=MyEnum.SomeValue;byte[]enumBytes=enumValue.ToByteArray();ByteArrayBuilder- Fluent builder for constructing byte arraysByteArrayExtensions- Extension methods for reading and manipulating byte arraysByteArrayAsyncExtensions- Asynchronous operations for file I/O and parallel processingByteArrayCompressionExtensions- Compression and decompression utilitiesByteArrayUtilities- Analysis, formatting, and performance measurement toolsByteArrayProtocolExtensions- Protocol parsing including TLV structuresObjectToByteArrayExtensions- Object-to-byte-array conversion helpers
- Primitives:
ToBoolean,ToByte,ToSByte,ToChar,ToInt16/32/64,ToUInt16/32/64 - Floating Point:
ToSingle,ToDouble,ToHalf - Strings:
ToUtf8String,ToAsciiString,ToHexString,ToBase64String - Date & Time:
ToDateTime,ToTimeSpan,ToDateTimeOffset,ToDateTimeFromUnixTimestamp - Network Types:
ToIPAddress,ToIPEndPoint, big-endian numeric conversions - Complex Types:
ToEnum<T>,ToVersion,ToGuid - Protocol Structures:
ParseTlv,ParseFixedLengthRecords - Safe Variants: All methods have
OrDefaultversions that return defaults instead of throwing
- Fluent Building:
Append<T>,AppendUtf8String,AppendAsciiString,AppendHexString,AppendBase64String - Direct Conversion:
Utf8StringToByteArray,HexStringToByteArray,ToByteArray<T> - Object Serialization: Convert any supported type to byte arrays
- File I/O:
WriteToFileAsync,ReadFromFileAsync,AppendToFileAsync - Parallel Processing:
ProcessInParallelAsync,TransformInParallelAsync - Cryptographic:
ComputeSha256Async,ComputeMd5Async,GenerateRandomBytesAsync
- Algorithms:
CompressGZip/DecompressGZip,CompressDeflate/DecompressDeflate,CompressBrotli/DecompressBrotli - Utilities: Compression ratio analysis and format detection
- Manipulation:
SafeSlice,Concatenate,TrimEnd,TrimEndNonDestructive,Reverse,Xor - Pattern Matching:
StartsWith,EndsWith,IndexOf,IsIdenticalTo - Analysis:
ToBinaryString,CalculateEntropy,AnalyzeDistribution - Debugging:
ToDebugString,ToHexDebugString, performance measurement
- Safety First: Explicit bounds checking with clear exception messages
- Zero-Allocation Friendly: Efficient operations using
ReadOnlySpan<byte>andSequenceEqual - Fail-Safe Defaults:
OrDefaultmethods never advance read cursors on failure - Type Safety: Strict enum conversion with validation for undefined values
- Cross-Platform: Optimized for .NET 9 and modern C# features
- Testing: xUnit + FluentAssertions with comprehensive coverage
- Build:
dotnet build - Test:
dotnet test - Framework: .NET 9.0
MIT — see LICENSE.md for details.
Designed for modern .NET applications requiring efficient, safe byte array operations.