Repository files navigation

🗂️ Plugin.ByteArrays

Icon

CI.NETNuGetNuGet DownloadsGitHub ReleaseLicenseGitHub Pages

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.


📦 Features

  • 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

🛠️ Supported Conversion Types

The following table shows all types that can be converted from byte arrays, with support across byte[], ReadOnlySpan<byte>, and ReadOnlyMemory<byte>:

TypeSize (bytes)byte[]ReadOnlySpan<byte>ReadOnlyMemory<byte>Notes
bool1➡️True[1] or False[0]
byte1➡️Unsigned 8-bit (0-255)
sbyte1➡️Signed 8-bit (-128 to 127)
char2➡️Unicode character
short2➡️Signed 16-bit (-32,768 to 32,767)
ushort2➡️Unsigned 16-bit (0 to 65,535)
int4➡️Signed 32-bit
uint4➡️Unsigned 32-bit
long8➡️Signed 64-bit
ulong8➡️Unsigned 64-bit
float4➡️Single-precision
double8➡️Double-precision
Half2➡️Half-precision
decimal16➡️High-precision decimal
DateTime8➡️Binary representation
TimeSpan8➡️Ticks representation
DateTimeOffset16/10➡️DateTime + offset
Guid16➡️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
Version16➡️.NET Version object
DateTime (Unix)4➡️Seconds since epoch

Legend

  • Fully Supported - All conversion methods available
  • Not Available - Type conversion not implemented
  • ➡️ Via Span - ReadOnlyMemory<byte> uses .Span property to access ReadOnlySpan<byte> methods

Method Variants Available

  • Standard: ToType(ref position) and ToType(position) - Throws on error
  • Safe: ToTypeOrDefault(ref position, defaultValue) and ToTypeOrDefault(position, defaultValue) - Returns default on error

Special Features

  • Position Tracking: ref int position parameter 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

🛠️ Usage Examples

ByteArrayBuilder

usingPlugin.ByteArrays;usingvarbuilder=newByteArrayBuilder();builder.Append(0x01).AppendUtf8String("Hello").Append(newbyte[]{0x02,0x03}).Append(42).AppendHexString("DEADBEEF");byte[]result=builder.ToByteArray();

Reading Primitives from Byte Arrays

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);

Array Manipulation

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});

Pattern Matching and Search

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);// true

String and Format Conversions

usingPlugin.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);

DateTime and Time Operations

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 TimeSpan

Network and Protocol Operations

usingPlugin.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)}");

Async Operations

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);

Compression

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})");

GUID Operations

usingPlugin.ByteArrays;// GUID conversionsvarguid=Guid.NewGuid();byte[]guidBytes=guid.ToByteArray();position=0;Guidrestored=guidBytes.ToGuid(refposition);// Safe GUID operationsGuidsafeGuid=invalidData.ToGuidOrDefault(refposition,Guid.Empty);

Utilities and Analysis

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");

Object Serialization

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();

📋 API Overview

Core Classes

  • ByteArrayBuilder - Fluent builder for constructing byte arrays
  • ByteArrayExtensions - Extension methods for reading and manipulating byte arrays
  • ByteArrayAsyncExtensions - Asynchronous operations for file I/O and parallel processing
  • ByteArrayCompressionExtensions - Compression and decompression utilities
  • ByteArrayUtilities - Analysis, formatting, and performance measurement tools
  • ByteArrayProtocolExtensions - Protocol parsing including TLV structures
  • ObjectToByteArrayExtensions - Object-to-byte-array conversion helpers

Reading Operations

  • 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 OrDefault versions that return defaults instead of throwing

Writing Operations

  • Fluent Building: Append<T>, AppendUtf8String, AppendAsciiString, AppendHexString, AppendBase64String
  • Direct Conversion: Utf8StringToByteArray, HexStringToByteArray, ToByteArray<T>
  • Object Serialization: Convert any supported type to byte arrays

Async File Operations

  • File I/O: WriteToFileAsync, ReadFromFileAsync, AppendToFileAsync
  • Parallel Processing: ProcessInParallelAsync, TransformInParallelAsync
  • Cryptographic: ComputeSha256Async, ComputeMd5Async, GenerateRandomBytesAsync

Compression Utilities

  • Algorithms: CompressGZip/DecompressGZip, CompressDeflate/DecompressDeflate, CompressBrotli/DecompressBrotli
  • Utilities: Compression ratio analysis and format detection

Array Operations

  • Manipulation: SafeSlice, Concatenate, TrimEnd, TrimEndNonDestructive, Reverse, Xor
  • Pattern Matching: StartsWith, EndsWith, IndexOf, IsIdenticalTo
  • Analysis: ToBinaryString, CalculateEntropy, AnalyzeDistribution
  • Debugging: ToDebugString, ToHexDebugString, performance measurement

🔧 Design Principles

  • Safety First: Explicit bounds checking with clear exception messages
  • Zero-Allocation Friendly: Efficient operations using ReadOnlySpan<byte> and SequenceEqual
  • Fail-Safe Defaults: OrDefault methods 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

🧪 Development

  • Testing: xUnit + FluentAssertions with comprehensive coverage
  • Build: dotnet build
  • Test: dotnet test
  • Framework: .NET 9.0

📄 License

MIT — see LICENSE.md for details.


Designed for modern .NET applications requiring efficient, safe byte array operations.

About

Comprehensive utilities for working with byte arrays in .NET — performance, safety and ease of use across all platforms

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

🗂️ Plugin.ByteArrays

Icon

CI.NETNuGetNuGet DownloadsGitHub ReleaseLicenseGitHub Pages

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.


📦 Features

  • 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

🛠️ Supported Conversion Types

The following table shows all types that can be converted from byte arrays, with support across byte[], ReadOnlySpan<byte>, and ReadOnlyMemory<byte>:

TypeSize (bytes)byte[]ReadOnlySpan<byte>ReadOnlyMemory<byte>Notes
bool1➡️True[1] or False[0]
byte1➡️Unsigned 8-bit (0-255)
sbyte1➡️Signed 8-bit (-128 to 127)
char2➡️Unicode character
short2➡️Signed 16-bit (-32,768 to 32,767)
ushort2➡️Unsigned 16-bit (0 to 65,535)
int4➡️Signed 32-bit
uint4➡️Unsigned 32-bit
long8➡️Signed 64-bit
ulong8➡️Unsigned 64-bit
float4➡️Single-precision
double8➡️Double-precision
Half2➡️Half-precision
decimal16➡️High-precision decimal
DateTime8➡️Binary representation
TimeSpan8➡️Ticks representation
DateTimeOffset16/10➡️DateTime + offset
Guid16➡️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
Version16➡️.NET Version object
DateTime (Unix)4➡️Seconds since epoch

Legend

  • Fully Supported - All conversion methods available
  • Not Available - Type conversion not implemented
  • ➡️ Via Span - ReadOnlyMemory<byte> uses .Span property to access ReadOnlySpan<byte> methods

Method Variants Available

  • Standard: ToType(ref position) and ToType(position) - Throws on error
  • Safe: ToTypeOrDefault(ref position, defaultValue) and ToTypeOrDefault(position, defaultValue) - Returns default on error

Special Features

  • Position Tracking: ref int position parameter 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

🛠️ Usage Examples

ByteArrayBuilder

usingPlugin.ByteArrays;usingvarbuilder=newByteArrayBuilder();builder.Append(0x01).AppendUtf8String("Hello").Append(newbyte[]{0x02,0x03}).Append(42).AppendHexString("DEADBEEF");byte[]result=builder.ToByteArray();

Reading Primitives from Byte Arrays

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);

Array Manipulation

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});

Pattern Matching and Search

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);// true

String and Format Conversions

usingPlugin.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);

DateTime and Time Operations

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 TimeSpan

Network and Protocol Operations

usingPlugin.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)}");

Async Operations

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);

Compression

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})");

GUID Operations

usingPlugin.ByteArrays;// GUID conversionsvarguid=Guid.NewGuid();byte[]guidBytes=guid.ToByteArray();position=0;Guidrestored=guidBytes.ToGuid(refposition);// Safe GUID operationsGuidsafeGuid=invalidData.ToGuidOrDefault(refposition,Guid.Empty);

Utilities and Analysis

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");

Object Serialization

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();

📋 API Overview

Core Classes

  • ByteArrayBuilder - Fluent builder for constructing byte arrays
  • ByteArrayExtensions - Extension methods for reading and manipulating byte arrays
  • ByteArrayAsyncExtensions - Asynchronous operations for file I/O and parallel processing
  • ByteArrayCompressionExtensions - Compression and decompression utilities
  • ByteArrayUtilities - Analysis, formatting, and performance measurement tools
  • ByteArrayProtocolExtensions - Protocol parsing including TLV structures
  • ObjectToByteArrayExtensions - Object-to-byte-array conversion helpers

Reading Operations

  • 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 OrDefault versions that return defaults instead of throwing

Writing Operations

  • Fluent Building: Append<T>, AppendUtf8String, AppendAsciiString, AppendHexString, AppendBase64String
  • Direct Conversion: Utf8StringToByteArray, HexStringToByteArray, ToByteArray<T>
  • Object Serialization: Convert any supported type to byte arrays

Async File Operations

  • File I/O: WriteToFileAsync, ReadFromFileAsync, AppendToFileAsync
  • Parallel Processing: ProcessInParallelAsync, TransformInParallelAsync
  • Cryptographic: ComputeSha256Async, ComputeMd5Async, GenerateRandomBytesAsync

Compression Utilities

  • Algorithms: CompressGZip/DecompressGZip, CompressDeflate/DecompressDeflate, CompressBrotli/DecompressBrotli
  • Utilities: Compression ratio analysis and format detection

Array Operations

  • Manipulation: SafeSlice, Concatenate, TrimEnd, TrimEndNonDestructive, Reverse, Xor
  • Pattern Matching: StartsWith, EndsWith, IndexOf, IsIdenticalTo
  • Analysis: ToBinaryString, CalculateEntropy, AnalyzeDistribution
  • Debugging: ToDebugString, ToHexDebugString, performance measurement

🔧 Design Principles

  • Safety First: Explicit bounds checking with clear exception messages
  • Zero-Allocation Friendly: Efficient operations using ReadOnlySpan<byte> and SequenceEqual
  • Fail-Safe Defaults: OrDefault methods 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

🧪 Development

  • Testing: xUnit + FluentAssertions with comprehensive coverage
  • Build: dotnet build
  • Test: dotnet test
  • Framework: .NET 9.0

📄 License

MIT — see LICENSE.md for details.


Designed for modern .NET applications requiring efficient, safe byte array operations.

About

Comprehensive utilities for working with byte arrays in .NET — performance, safety and ease of use across all platforms

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

🗂️ Plugin.ByteArrays

Icon

CI.NETNuGetNuGet DownloadsGitHub ReleaseLicenseGitHub Pages

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.


📦 Features

  • 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

🛠️ Supported Conversion Types

The following table shows all types that can be converted from byte arrays, with support across byte[], ReadOnlySpan<byte>, and ReadOnlyMemory<byte>:

TypeSize (bytes)byte[]ReadOnlySpan<byte>ReadOnlyMemory<byte>Notes
bool1➡️True[1] or False[0]
byte1➡️Unsigned 8-bit (0-255)
sbyte1➡️Signed 8-bit (-128 to 127)
char2➡️Unicode character
short2➡️Signed 16-bit (-32,768 to 32,767)
ushort2➡️Unsigned 16-bit (0 to 65,535)
int4➡️Signed 32-bit
uint4➡️Unsigned 32-bit
long8➡️Signed 64-bit
ulong8➡️Unsigned 64-bit
float4➡️Single-precision
double8➡️Double-precision
Half2➡️Half-precision
decimal16➡️High-precision decimal
DateTime8➡️Binary representation
TimeSpan8➡️Ticks representation
DateTimeOffset16/10➡️DateTime + offset
Guid16➡️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
Version16➡️.NET Version object
DateTime (Unix)4➡️Seconds since epoch

Legend

  • Fully Supported - All conversion methods available
  • Not Available - Type conversion not implemented
  • ➡️ Via Span - ReadOnlyMemory<byte> uses .Span property to access ReadOnlySpan<byte> methods

Method Variants Available

  • Standard: ToType(ref position) and ToType(position) - Throws on error
  • Safe: ToTypeOrDefault(ref position, defaultValue) and ToTypeOrDefault(position, defaultValue) - Returns default on error

Special Features

  • Position Tracking: ref int position parameter 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

🛠️ Usage Examples

ByteArrayBuilder

usingPlugin.ByteArrays;usingvarbuilder=newByteArrayBuilder();builder.Append(0x01).AppendUtf8String("Hello").Append(newbyte[]{0x02,0x03}).Append(42).AppendHexString("DEADBEEF");byte[]result=builder.ToByteArray();

Reading Primitives from Byte Arrays

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);

Array Manipulation

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});

Pattern Matching and Search

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);// true

String and Format Conversions

usingPlugin.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);

DateTime and Time Operations

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 TimeSpan

Network and Protocol Operations

usingPlugin.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)}");

Async Operations

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);

Compression

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})");

GUID Operations

usingPlugin.ByteArrays;// GUID conversionsvarguid=Guid.NewGuid();byte[]guidBytes=guid.ToByteArray();position=0;Guidrestored=guidBytes.ToGuid(refposition);// Safe GUID operationsGuidsafeGuid=invalidData.ToGuidOrDefault(refposition,Guid.Empty);

Utilities and Analysis

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");

Object Serialization

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();

📋 API Overview

Core Classes

  • ByteArrayBuilder - Fluent builder for constructing byte arrays
  • ByteArrayExtensions - Extension methods for reading and manipulating byte arrays
  • ByteArrayAsyncExtensions - Asynchronous operations for file I/O and parallel processing
  • ByteArrayCompressionExtensions - Compression and decompression utilities
  • ByteArrayUtilities - Analysis, formatting, and performance measurement tools
  • ByteArrayProtocolExtensions - Protocol parsing including TLV structures
  • ObjectToByteArrayExtensions - Object-to-byte-array conversion helpers

Reading Operations

  • 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 OrDefault versions that return defaults instead of throwing

Writing Operations

  • Fluent Building: Append<T>, AppendUtf8String, AppendAsciiString, AppendHexString, AppendBase64String
  • Direct Conversion: Utf8StringToByteArray, HexStringToByteArray, ToByteArray<T>
  • Object Serialization: Convert any supported type to byte arrays

Async File Operations

  • File I/O: WriteToFileAsync, ReadFromFileAsync, AppendToFileAsync
  • Parallel Processing: ProcessInParallelAsync, TransformInParallelAsync
  • Cryptographic: ComputeSha256Async, ComputeMd5Async, GenerateRandomBytesAsync

Compression Utilities

  • Algorithms: CompressGZip/DecompressGZip, CompressDeflate/DecompressDeflate, CompressBrotli/DecompressBrotli
  • Utilities: Compression ratio analysis and format detection

Array Operations

  • Manipulation: SafeSlice, Concatenate, TrimEnd, TrimEndNonDestructive, Reverse, Xor
  • Pattern Matching: StartsWith, EndsWith, IndexOf, IsIdenticalTo
  • Analysis: ToBinaryString, CalculateEntropy, AnalyzeDistribution
  • Debugging: ToDebugString, ToHexDebugString, performance measurement

🔧 Design Principles

  • Safety First: Explicit bounds checking with clear exception messages
  • Zero-Allocation Friendly: Efficient operations using ReadOnlySpan<byte> and SequenceEqual
  • Fail-Safe Defaults: OrDefault methods 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

🧪 Development

  • Testing: xUnit + FluentAssertions with comprehensive coverage
  • Build: dotnet build
  • Test: dotnet test
  • Framework: .NET 9.0

📄 License

MIT — see LICENSE.md for details.


Designed for modern .NET applications requiring efficient, safe byte array operations.

About

Comprehensive utilities for working with byte arrays in .NET — performance, safety and ease of use across all platforms

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

🗂️ Plugin.ByteArrays

Icon

CI.NETNuGetNuGet DownloadsGitHub ReleaseLicenseGitHub Pages

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.


📦 Features

  • 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

🛠️ Supported Conversion Types

The following table shows all types that can be converted from byte arrays, with support across byte[], ReadOnlySpan<byte>, and ReadOnlyMemory<byte>:

TypeSize (bytes)byte[]ReadOnlySpan<byte>ReadOnlyMemory<byte>Notes
bool1➡️True[1] or False[0]
byte1➡️Unsigned 8-bit (0-255)
sbyte1➡️Signed 8-bit (-128 to 127)
char2➡️Unicode character
short2➡️Signed 16-bit (-32,768 to 32,767)
ushort2➡️Unsigned 16-bit (0 to 65,535)
int4➡️Signed 32-bit
uint4➡️Unsigned 32-bit
long8➡️Signed 64-bit
ulong8➡️Unsigned 64-bit
float4➡️Single-precision
double8➡️Double-precision
Half2➡️Half-precision
decimal16➡️High-precision decimal
DateTime8➡️Binary representation
TimeSpan8➡️Ticks representation
DateTimeOffset16/10➡️DateTime + offset
Guid16➡️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
Version16➡️.NET Version object
DateTime (Unix)4➡️Seconds since epoch

Legend

  • Fully Supported - All conversion methods available
  • Not Available - Type conversion not implemented
  • ➡️ Via Span - ReadOnlyMemory<byte> uses .Span property to access ReadOnlySpan<byte> methods

Method Variants Available

  • Standard: ToType(ref position) and ToType(position) - Throws on error
  • Safe: ToTypeOrDefault(ref position, defaultValue) and ToTypeOrDefault(position, defaultValue) - Returns default on error

Special Features

  • Position Tracking: ref int position parameter 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

🛠️ Usage Examples

ByteArrayBuilder

usingPlugin.ByteArrays;usingvarbuilder=newByteArrayBuilder();builder.Append(0x01).AppendUtf8String("Hello").Append(newbyte[]{0x02,0x03}).Append(42).AppendHexString("DEADBEEF");byte[]result=builder.ToByteArray();

Reading Primitives from Byte Arrays

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);

Array Manipulation

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});

Pattern Matching and Search

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);// true

String and Format Conversions

usingPlugin.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);

DateTime and Time Operations

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 TimeSpan

Network and Protocol Operations

usingPlugin.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)}");

Async Operations

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);

Compression

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})");

GUID Operations

usingPlugin.ByteArrays;// GUID conversionsvarguid=Guid.NewGuid();byte[]guidBytes=guid.ToByteArray();position=0;Guidrestored=guidBytes.ToGuid(refposition);// Safe GUID operationsGuidsafeGuid=invalidData.ToGuidOrDefault(refposition,Guid.Empty);

Utilities and Analysis

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");

Object Serialization

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();

📋 API Overview

Core Classes

  • ByteArrayBuilder - Fluent builder for constructing byte arrays
  • ByteArrayExtensions - Extension methods for reading and manipulating byte arrays
  • ByteArrayAsyncExtensions - Asynchronous operations for file I/O and parallel processing
  • ByteArrayCompressionExtensions - Compression and decompression utilities
  • ByteArrayUtilities - Analysis, formatting, and performance measurement tools
  • ByteArrayProtocolExtensions - Protocol parsing including TLV structures
  • ObjectToByteArrayExtensions - Object-to-byte-array conversion helpers

Reading Operations

  • 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 OrDefault versions that return defaults instead of throwing

Writing Operations

  • Fluent Building: Append<T>, AppendUtf8String, AppendAsciiString, AppendHexString, AppendBase64String
  • Direct Conversion: Utf8StringToByteArray, HexStringToByteArray, ToByteArray<T>
  • Object Serialization: Convert any supported type to byte arrays

Async File Operations

  • File I/O: WriteToFileAsync, ReadFromFileAsync, AppendToFileAsync
  • Parallel Processing: ProcessInParallelAsync, TransformInParallelAsync
  • Cryptographic: ComputeSha256Async, ComputeMd5Async, GenerateRandomBytesAsync

Compression Utilities

  • Algorithms: CompressGZip/DecompressGZip, CompressDeflate/DecompressDeflate, CompressBrotli/DecompressBrotli
  • Utilities: Compression ratio analysis and format detection

Array Operations

  • Manipulation: SafeSlice, Concatenate, TrimEnd, TrimEndNonDestructive, Reverse, Xor
  • Pattern Matching: StartsWith, EndsWith, IndexOf, IsIdenticalTo
  • Analysis: ToBinaryString, CalculateEntropy, AnalyzeDistribution
  • Debugging: ToDebugString, ToHexDebugString, performance measurement

🔧 Design Principles

  • Safety First: Explicit bounds checking with clear exception messages
  • Zero-Allocation Friendly: Efficient operations using ReadOnlySpan<byte> and SequenceEqual
  • Fail-Safe Defaults: OrDefault methods 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

🧪 Development

  • Testing: xUnit + FluentAssertions with comprehensive coverage
  • Build: dotnet build
  • Test: dotnet test
  • Framework: .NET 9.0

📄 License

MIT — see LICENSE.md for details.


Designed for modern .NET applications requiring efficient, safe byte array operations.

About

Comprehensive utilities for working with byte arrays in .NET — performance, safety and ease of use across all platforms

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

🗂️ Plugin.ByteArrays

Icon

CI.NETNuGetNuGet DownloadsGitHub ReleaseLicenseGitHub Pages

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.


📦 Features

  • 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

🛠️ Supported Conversion Types

The following table shows all types that can be converted from byte arrays, with support across byte[], ReadOnlySpan<byte>, and ReadOnlyMemory<byte>:

TypeSize (bytes)byte[]ReadOnlySpan<byte>ReadOnlyMemory<byte>Notes
bool1➡️True[1] or False[0]
byte1➡️Unsigned 8-bit (0-255)
sbyte1➡️Signed 8-bit (-128 to 127)
char2➡️Unicode character
short2➡️Signed 16-bit (-32,768 to 32,767)
ushort2➡️Unsigned 16-bit (0 to 65,535)
int4➡️Signed 32-bit
uint4➡️Unsigned 32-bit
long8➡️Signed 64-bit
ulong8➡️Unsigned 64-bit
float4➡️Single-precision
double8➡️Double-precision
Half2➡️Half-precision
decimal16➡️High-precision decimal
DateTime8➡️Binary representation
TimeSpan8➡️Ticks representation
DateTimeOffset16/10➡️DateTime + offset
Guid16➡️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
Version16➡️.NET Version object
DateTime (Unix)4➡️Seconds since epoch

Legend

  • Fully Supported - All conversion methods available
  • Not Available - Type conversion not implemented
  • ➡️ Via Span - ReadOnlyMemory<byte> uses .Span property to access ReadOnlySpan<byte> methods

Method Variants Available

  • Standard: ToType(ref position) and ToType(position) - Throws on error
  • Safe: ToTypeOrDefault(ref position, defaultValue) and ToTypeOrDefault(position, defaultValue) - Returns default on error

Special Features

  • Position Tracking: ref int position parameter 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

🛠️ Usage Examples

ByteArrayBuilder

usingPlugin.ByteArrays;usingvarbuilder=newByteArrayBuilder();builder.Append(0x01).AppendUtf8String("Hello").Append(newbyte[]{0x02,0x03}).Append(42).AppendHexString("DEADBEEF");byte[]result=builder.ToByteArray();

Reading Primitives from Byte Arrays

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);

Array Manipulation

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});

Pattern Matching and Search

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);// true

String and Format Conversions

usingPlugin.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);

DateTime and Time Operations

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 TimeSpan

Network and Protocol Operations

usingPlugin.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)}");

Async Operations

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);

Compression

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})");

GUID Operations

usingPlugin.ByteArrays;// GUID conversionsvarguid=Guid.NewGuid();byte[]guidBytes=guid.ToByteArray();position=0;Guidrestored=guidBytes.ToGuid(refposition);// Safe GUID operationsGuidsafeGuid=invalidData.ToGuidOrDefault(refposition,Guid.Empty);

Utilities and Analysis

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");

Object Serialization

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();

📋 API Overview

Core Classes

  • ByteArrayBuilder - Fluent builder for constructing byte arrays
  • ByteArrayExtensions - Extension methods for reading and manipulating byte arrays
  • ByteArrayAsyncExtensions - Asynchronous operations for file I/O and parallel processing
  • ByteArrayCompressionExtensions - Compression and decompression utilities
  • ByteArrayUtilities - Analysis, formatting, and performance measurement tools
  • ByteArrayProtocolExtensions - Protocol parsing including TLV structures
  • ObjectToByteArrayExtensions - Object-to-byte-array conversion helpers

Reading Operations

  • 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 OrDefault versions that return defaults instead of throwing

Writing Operations

  • Fluent Building: Append<T>, AppendUtf8String, AppendAsciiString, AppendHexString, AppendBase64String
  • Direct Conversion: Utf8StringToByteArray, HexStringToByteArray, ToByteArray<T>
  • Object Serialization: Convert any supported type to byte arrays

Async File Operations

  • File I/O: WriteToFileAsync, ReadFromFileAsync, AppendToFileAsync
  • Parallel Processing: ProcessInParallelAsync, TransformInParallelAsync
  • Cryptographic: ComputeSha256Async, ComputeMd5Async, GenerateRandomBytesAsync

Compression Utilities

  • Algorithms: CompressGZip/DecompressGZip, CompressDeflate/DecompressDeflate, CompressBrotli/DecompressBrotli
  • Utilities: Compression ratio analysis and format detection

Array Operations

  • Manipulation: SafeSlice, Concatenate, TrimEnd, TrimEndNonDestructive, Reverse, Xor
  • Pattern Matching: StartsWith, EndsWith, IndexOf, IsIdenticalTo
  • Analysis: ToBinaryString, CalculateEntropy, AnalyzeDistribution
  • Debugging: ToDebugString, ToHexDebugString, performance measurement

🔧 Design Principles

  • Safety First: Explicit bounds checking with clear exception messages
  • Zero-Allocation Friendly: Efficient operations using ReadOnlySpan<byte> and SequenceEqual
  • Fail-Safe Defaults: OrDefault methods 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

🧪 Development

  • Testing: xUnit + FluentAssertions with comprehensive coverage
  • Build: dotnet build
  • Test: dotnet test
  • Framework: .NET 9.0

📄 License

MIT — see LICENSE.md for details.


Designed for modern .NET applications requiring efficient, safe byte array operations.

About

Comprehensive utilities for working with byte arrays in .NET — performance, safety and ease of use across all platforms

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

🗂️ Plugin.ByteArrays

Icon

CI.NETNuGetNuGet DownloadsGitHub ReleaseLicenseGitHub Pages

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.


📦 Features

  • 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

🛠️ Supported Conversion Types

The following table shows all types that can be converted from byte arrays, with support across byte[], ReadOnlySpan<byte>, and ReadOnlyMemory<byte>:

TypeSize (bytes)byte[]ReadOnlySpan<byte>ReadOnlyMemory<byte>Notes
bool1➡️True[1] or False[0]
byte1➡️Unsigned 8-bit (0-255)
sbyte1➡️Signed 8-bit (-128 to 127)
char2➡️Unicode character
short2➡️Signed 16-bit (-32,768 to 32,767)
ushort2➡️Unsigned 16-bit (0 to 65,535)
int4➡️Signed 32-bit
uint4➡️Unsigned 32-bit
long8➡️Signed 64-bit
ulong8➡️Unsigned 64-bit
float4➡️Single-precision
double8➡️Double-precision
Half2➡️Half-precision
decimal16➡️High-precision decimal
DateTime8➡️Binary representation
TimeSpan8➡️Ticks representation
DateTimeOffset16/10➡️DateTime + offset
Guid16➡️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
Version16➡️.NET Version object
DateTime (Unix)4➡️Seconds since epoch

Legend

  • Fully Supported - All conversion methods available
  • Not Available - Type conversion not implemented
  • ➡️ Via Span - ReadOnlyMemory<byte> uses .Span property to access ReadOnlySpan<byte> methods

Method Variants Available

  • Standard: ToType(ref position) and ToType(position) - Throws on error
  • Safe: ToTypeOrDefault(ref position, defaultValue) and ToTypeOrDefault(position, defaultValue) - Returns default on error

Special Features

  • Position Tracking: ref int position parameter 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

🛠️ Usage Examples

ByteArrayBuilder

usingPlugin.ByteArrays;usingvarbuilder=newByteArrayBuilder();builder.Append(0x01).AppendUtf8String("Hello").Append(newbyte[]{0x02,0x03}).Append(42).AppendHexString("DEADBEEF");byte[]result=builder.ToByteArray();

Reading Primitives from Byte Arrays

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);

Array Manipulation

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});

Pattern Matching and Search

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);// true

String and Format Conversions

usingPlugin.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);

DateTime and Time Operations

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 TimeSpan

Network and Protocol Operations

usingPlugin.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)}");

Async Operations

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);

Compression

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})");

GUID Operations

usingPlugin.ByteArrays;// GUID conversionsvarguid=Guid.NewGuid();byte[]guidBytes=guid.ToByteArray();position=0;Guidrestored=guidBytes.ToGuid(refposition);// Safe GUID operationsGuidsafeGuid=invalidData.ToGuidOrDefault(refposition,Guid.Empty);

Utilities and Analysis

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");

Object Serialization

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();

📋 API Overview

Core Classes

  • ByteArrayBuilder - Fluent builder for constructing byte arrays
  • ByteArrayExtensions - Extension methods for reading and manipulating byte arrays
  • ByteArrayAsyncExtensions - Asynchronous operations for file I/O and parallel processing
  • ByteArrayCompressionExtensions - Compression and decompression utilities
  • ByteArrayUtilities - Analysis, formatting, and performance measurement tools
  • ByteArrayProtocolExtensions - Protocol parsing including TLV structures
  • ObjectToByteArrayExtensions - Object-to-byte-array conversion helpers

Reading Operations

  • 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 OrDefault versions that return defaults instead of throwing

Writing Operations

  • Fluent Building: Append<T>, AppendUtf8String, AppendAsciiString, AppendHexString, AppendBase64String
  • Direct Conversion: Utf8StringToByteArray, HexStringToByteArray, ToByteArray<T>
  • Object Serialization: Convert any supported type to byte arrays

Async File Operations

  • File I/O: WriteToFileAsync, ReadFromFileAsync, AppendToFileAsync
  • Parallel Processing: ProcessInParallelAsync, TransformInParallelAsync
  • Cryptographic: ComputeSha256Async, ComputeMd5Async, GenerateRandomBytesAsync

Compression Utilities

  • Algorithms: CompressGZip/DecompressGZip, CompressDeflate/DecompressDeflate, CompressBrotli/DecompressBrotli
  • Utilities: Compression ratio analysis and format detection

Array Operations

  • Manipulation: SafeSlice, Concatenate, TrimEnd, TrimEndNonDestructive, Reverse, Xor
  • Pattern Matching: StartsWith, EndsWith, IndexOf, IsIdenticalTo
  • Analysis: ToBinaryString, CalculateEntropy, AnalyzeDistribution
  • Debugging: ToDebugString, ToHexDebugString, performance measurement

🔧 Design Principles

  • Safety First: Explicit bounds checking with clear exception messages
  • Zero-Allocation Friendly: Efficient operations using ReadOnlySpan<byte> and SequenceEqual
  • Fail-Safe Defaults: OrDefault methods 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

🧪 Development

  • Testing: xUnit + FluentAssertions with comprehensive coverage
  • Build: dotnet build
  • Test: dotnet test
  • Framework: .NET 9.0

📄 License

MIT — see LICENSE.md for details.


Designed for modern .NET applications requiring efficient, safe byte array operations.

About

Comprehensive utilities for working with byte arrays in .NET — performance, safety and ease of use across all platforms

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

🗂️ Plugin.ByteArrays

Icon

CI.NETNuGetNuGet DownloadsGitHub ReleaseLicenseGitHub Pages

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.


📦 Features

  • 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

🛠️ Supported Conversion Types

The following table shows all types that can be converted from byte arrays, with support across byte[], ReadOnlySpan<byte>, and ReadOnlyMemory<byte>:

TypeSize (bytes)byte[]ReadOnlySpan<byte>ReadOnlyMemory<byte>Notes
bool1➡️True[1] or False[0]
byte1➡️Unsigned 8-bit (0-255)
sbyte1➡️Signed 8-bit (-128 to 127)
char2➡️Unicode character
short2➡️Signed 16-bit (-32,768 to 32,767)
ushort2➡️Unsigned 16-bit (0 to 65,535)
int4➡️Signed 32-bit
uint4➡️Unsigned 32-bit
long8➡️Signed 64-bit
ulong8➡️Unsigned 64-bit
float4➡️Single-precision
double8➡️Double-precision
Half2➡️Half-precision
decimal16➡️High-precision decimal
DateTime8➡️Binary representation
TimeSpan8➡️Ticks representation
DateTimeOffset16/10➡️DateTime + offset
Guid16➡️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
Version16➡️.NET Version object
DateTime (Unix)4➡️Seconds since epoch

Legend

  • Fully Supported - All conversion methods available
  • Not Available - Type conversion not implemented
  • ➡️ Via Span - ReadOnlyMemory<byte> uses .Span property to access ReadOnlySpan<byte> methods

Method Variants Available

  • Standard: ToType(ref position) and ToType(position) - Throws on error
  • Safe: ToTypeOrDefault(ref position, defaultValue) and ToTypeOrDefault(position, defaultValue) - Returns default on error

Special Features

  • Position Tracking: ref int position parameter 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

🛠️ Usage Examples

ByteArrayBuilder

usingPlugin.ByteArrays;usingvarbuilder=newByteArrayBuilder();builder.Append(0x01).AppendUtf8String("Hello").Append(newbyte[]{0x02,0x03}).Append(42).AppendHexString("DEADBEEF");byte[]result=builder.ToByteArray();

Reading Primitives from Byte Arrays

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);

Array Manipulation

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});

Pattern Matching and Search

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);// true

String and Format Conversions

usingPlugin.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);

DateTime and Time Operations

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 TimeSpan

Network and Protocol Operations

usingPlugin.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)}");

Async Operations

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);

Compression

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})");

GUID Operations

usingPlugin.ByteArrays;// GUID conversionsvarguid=Guid.NewGuid();byte[]guidBytes=guid.ToByteArray();position=0;Guidrestored=guidBytes.ToGuid(refposition);// Safe GUID operationsGuidsafeGuid=invalidData.ToGuidOrDefault(refposition,Guid.Empty);

Utilities and Analysis

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");

Object Serialization

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();

📋 API Overview

Core Classes

  • ByteArrayBuilder - Fluent builder for constructing byte arrays
  • ByteArrayExtensions - Extension methods for reading and manipulating byte arrays
  • ByteArrayAsyncExtensions - Asynchronous operations for file I/O and parallel processing
  • ByteArrayCompressionExtensions - Compression and decompression utilities
  • ByteArrayUtilities - Analysis, formatting, and performance measurement tools
  • ByteArrayProtocolExtensions - Protocol parsing including TLV structures
  • ObjectToByteArrayExtensions - Object-to-byte-array conversion helpers

Reading Operations

  • 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 OrDefault versions that return defaults instead of throwing

Writing Operations

  • Fluent Building: Append<T>, AppendUtf8String, AppendAsciiString, AppendHexString, AppendBase64String
  • Direct Conversion: Utf8StringToByteArray, HexStringToByteArray, ToByteArray<T>
  • Object Serialization: Convert any supported type to byte arrays

Async File Operations

  • File I/O: WriteToFileAsync, ReadFromFileAsync, AppendToFileAsync
  • Parallel Processing: ProcessInParallelAsync, TransformInParallelAsync
  • Cryptographic: ComputeSha256Async, ComputeMd5Async, GenerateRandomBytesAsync

Compression Utilities

  • Algorithms: CompressGZip/DecompressGZip, CompressDeflate/DecompressDeflate, CompressBrotli/DecompressBrotli
  • Utilities: Compression ratio analysis and format detection

Array Operations

  • Manipulation: SafeSlice, Concatenate, TrimEnd, TrimEndNonDestructive, Reverse, Xor
  • Pattern Matching: StartsWith, EndsWith, IndexOf, IsIdenticalTo
  • Analysis: ToBinaryString, CalculateEntropy, AnalyzeDistribution
  • Debugging: ToDebugString, ToHexDebugString, performance measurement

🔧 Design Principles

  • Safety First: Explicit bounds checking with clear exception messages
  • Zero-Allocation Friendly: Efficient operations using ReadOnlySpan<byte> and SequenceEqual
  • Fail-Safe Defaults: OrDefault methods 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

🧪 Development

  • Testing: xUnit + FluentAssertions with comprehensive coverage
  • Build: dotnet build
  • Test: dotnet test
  • Framework: .NET 9.0

📄 License

MIT — see LICENSE.md for details.


Designed for modern .NET applications requiring efficient, safe byte array operations.

About

Comprehensive utilities for working with byte arrays in .NET — performance, safety and ease of use across all platforms

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

🗂️ Plugin.ByteArrays

Icon

CI.NETNuGetNuGet DownloadsGitHub ReleaseLicenseGitHub Pages

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.


📦 Features

  • 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

🛠️ Supported Conversion Types

The following table shows all types that can be converted from byte arrays, with support across byte[], ReadOnlySpan<byte>, and ReadOnlyMemory<byte>:

TypeSize (bytes)byte[]ReadOnlySpan<byte>ReadOnlyMemory<byte>Notes
bool1➡️True[1] or False[0]
byte1➡️Unsigned 8-bit (0-255)
sbyte1➡️Signed 8-bit (-128 to 127)
char2➡️Unicode character
short2➡️Signed 16-bit (-32,768 to 32,767)
ushort2➡️Unsigned 16-bit (0 to 65,535)
int4➡️Signed 32-bit
uint4➡️Unsigned 32-bit
long8➡️Signed 64-bit
ulong8➡️Unsigned 64-bit
float4➡️Single-precision
double8➡️Double-precision
Half2➡️Half-precision
decimal16➡️High-precision decimal
DateTime8➡️Binary representation
TimeSpan8➡️Ticks representation
DateTimeOffset16/10➡️DateTime + offset
Guid16➡️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
Version16➡️.NET Version object
DateTime (Unix)4➡️Seconds since epoch

Legend

  • Fully Supported - All conversion methods available
  • Not Available - Type conversion not implemented
  • ➡️ Via Span - ReadOnlyMemory<byte> uses .Span property to access ReadOnlySpan<byte> methods

Method Variants Available

  • Standard: ToType(ref position) and ToType(position) - Throws on error
  • Safe: ToTypeOrDefault(ref position, defaultValue) and ToTypeOrDefault(position, defaultValue) - Returns default on error

Special Features

  • Position Tracking: ref int position parameter 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

🛠️ Usage Examples

ByteArrayBuilder

usingPlugin.ByteArrays;usingvarbuilder=newByteArrayBuilder();builder.Append(0x01).AppendUtf8String("Hello").Append(newbyte[]{0x02,0x03}).Append(42).AppendHexString("DEADBEEF");byte[]result=builder.ToByteArray();

Reading Primitives from Byte Arrays

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);

Array Manipulation

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});

Pattern Matching and Search

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);// true

String and Format Conversions

usingPlugin.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);

DateTime and Time Operations

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 TimeSpan

Network and Protocol Operations

usingPlugin.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)}");

Async Operations

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);

Compression

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})");

GUID Operations

usingPlugin.ByteArrays;// GUID conversionsvarguid=Guid.NewGuid();byte[]guidBytes=guid.ToByteArray();position=0;Guidrestored=guidBytes.ToGuid(refposition);// Safe GUID operationsGuidsafeGuid=invalidData.ToGuidOrDefault(refposition,Guid.Empty);

Utilities and Analysis

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");

Object Serialization

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();

📋 API Overview

Core Classes

  • ByteArrayBuilder - Fluent builder for constructing byte arrays
  • ByteArrayExtensions - Extension methods for reading and manipulating byte arrays
  • ByteArrayAsyncExtensions - Asynchronous operations for file I/O and parallel processing
  • ByteArrayCompressionExtensions - Compression and decompression utilities
  • ByteArrayUtilities - Analysis, formatting, and performance measurement tools
  • ByteArrayProtocolExtensions - Protocol parsing including TLV structures
  • ObjectToByteArrayExtensions - Object-to-byte-array conversion helpers

Reading Operations

  • 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 OrDefault versions that return defaults instead of throwing

Writing Operations

  • Fluent Building: Append<T>, AppendUtf8String, AppendAsciiString, AppendHexString, AppendBase64String
  • Direct Conversion: Utf8StringToByteArray, HexStringToByteArray, ToByteArray<T>
  • Object Serialization: Convert any supported type to byte arrays

Async File Operations

  • File I/O: WriteToFileAsync, ReadFromFileAsync, AppendToFileAsync
  • Parallel Processing: ProcessInParallelAsync, TransformInParallelAsync
  • Cryptographic: ComputeSha256Async, ComputeMd5Async, GenerateRandomBytesAsync

Compression Utilities

  • Algorithms: CompressGZip/DecompressGZip, CompressDeflate/DecompressDeflate, CompressBrotli/DecompressBrotli
  • Utilities: Compression ratio analysis and format detection

Array Operations

  • Manipulation: SafeSlice, Concatenate, TrimEnd, TrimEndNonDestructive, Reverse, Xor
  • Pattern Matching: StartsWith, EndsWith, IndexOf, IsIdenticalTo
  • Analysis: ToBinaryString, CalculateEntropy, AnalyzeDistribution
  • Debugging: ToDebugString, ToHexDebugString, performance measurement

🔧 Design Principles

  • Safety First: Explicit bounds checking with clear exception messages
  • Zero-Allocation Friendly: Efficient operations using ReadOnlySpan<byte> and SequenceEqual
  • Fail-Safe Defaults: OrDefault methods 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

🧪 Development

  • Testing: xUnit + FluentAssertions with comprehensive coverage
  • Build: dotnet build
  • Test: dotnet test
  • Framework: .NET 9.0

📄 License

MIT — see LICENSE.md for details.


Designed for modern .NET applications requiring efficient, safe byte array operations.

About

Comprehensive utilities for working with byte arrays in .NET — performance, safety and ease of use across all platforms

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages