byte Array Example
This page was last reviewed on Sep 14, 2023.
Dot Net Perls
Byte array. A byte array can store binary data in C# programs. This data may be part of a data file, image file, compressed file or downloaded server response.
Shows a byte array
With byte arrays, we have an ideal representation of this data. The byte array type allows us to store low-level representations. It is useful in optimization.
byte, sbyte
Display example. To begin, we create a small byte array in a C# program. Byte arrays can represent any values, but each individual byte can only hold a certain range.
Part 1 We create a byte array of 3 bytes. We store the minimum byte value, and the maximum byte value, in the array elements.
Part 2 We use a foreach-loop to display all the byte elements in the byte array.
Shows a byte array
using System; // Part 1: create byte array. byte[] data = new byte[3]; data[0] = byte.MinValue; data[1] = 0; data[2] = byte.MaxValue; // Part 2: display byte data. foreach (var element in data) { Console.WriteLine(element); }
0 0 255
Memory example. Here we allocate a byte array on the managed heap. The program measures the memory usage of the managed heap before and after this allocation occurs.
Detail The GC.GetTotalMemory method gathers the memory usage figures from the system before and after the allocation of the byte array.
Then The byte array variable is assigned a reference to 3 million bytes in an array allocated on the managed heap.
Result Allocating a 3 million element array of bytes causes 3 million bytes to be added to the memory usage of the program.
Tip Here we find that a byte array is a precise representation of bytes, not a higher-level construct.
using System; byte[] array1 = null; // // Allocate three million bytes and measure memory usage. // long bytes1 = GC.GetTotalMemory(false); array1 = new byte[1000 * 1000 * 3]; array1[0] = 0; long bytes2 = GC.GetTotalMemory(false); Console.WriteLine(bytes2 - bytes1);
Read bytes. We read in a byte array from a file with the System.IO namespace. An easy way to read a file into a binary array is the File.ReadAllBytes method in the File class.
using System; using System.IO; class Program { static void Main() { byte[] array = File.ReadAllBytes("C:\\profiles\\file.bin"); Console.WriteLine(array[0]); Console.WriteLine(array[1]); Console.WriteLine(array[2]); } }
56 66 80
ToBase64String. When we have a byte array, we do not just need to leave the data as a byte array. We can convert it to a string with ToBase64String.
Here We load a JPG image on the disk into a byte array, and then encode it as a string. This can be put in CSS or HTML files directly.
using System; using System.IO; class Program { static void Main() { byte[] data = File.ReadAllBytes(@"C:\perls\i\2d-adventurers-map-background.jpg"); // Get base 64. string result = Convert.ToBase64String(data); // Write first 20 chars. Console.WriteLine("BASE64: " + result.Substring(0, 20) + "..."); } }
BASE64: /9j/2wCEAAgGBgYGBggG...
Test byte array. A GZIP file must have certain bytes in its first few bytes. We use IsGZipHeader to test a byte array to see if it contains GZIP data.
Note The first part of Main reads in a GZIP file, "2About.gz". The result value from IsGZipHeader on this file is true.
Note 2 GZipTool is a public static class, which means you can access it from other namespaces and files. It contains IsGZipHeader.
Info IsGZipHeader returns true if the byte data passed to it contains the values 31 and 139 in its first two bytes.
using System; using System.IO; class Program { static void Main() { byte[] gzip = File.ReadAllBytes("2About.gz"); Console.WriteLine(GZipTool.IsGZipHeader(gzip)); byte[] text = File.ReadAllBytes("Program.cs"); Console.WriteLine(GZipTool.IsGZipHeader(text)); } } /// <summary> /// GZIP utility methods. /// </summary> public static class GZipTool { /// <summary> /// Checks the first two bytes in a GZIP file, which must be 31 and 139. /// </summary> public static bool IsGZipHeader(byte[] arr) { return arr.Length >= 2 && arr[0] == 31 && arr[1] == 139; } }
True False
Seek, read. We use Seek() on some Stream classes to read a part of a file into a byte array. It is faster to read in an entire byte array at once. This uses the file system's buffering.
File Seek
WebClient. We can download data over the Internet (or other net work) with a network connection with WebClient. We directly access the bytes of any server's response.
GZipStream. This allows us to use a byte array buffer for expanding or compressing GZIP-encoded data. This is an easy way to implement compression or decompression for web applications.
BinaryReader. This class allows us to imperatively read in a binary file with more helper methods than testing the bytes yourself.
A review. In C# programs we often use the byte array type. It stores data in a compact way, with minimal overhead. We provided pointers to further information on this type.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 14, 2023 (simplify).
© 2007-2024 Sam Allen.