TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# BitConverter Examples

Use the BitConverter class to change representations of types.
BitConverter converts representations. It changes a range of bytes to a different value type such as an int or double. This type contains utility methods. It is useful when manipulating or reading binary data.BitArray
To start, this program shows how to use the BitConverter class and its static methods ToInt32 and ToUInt32. These methods convert the byte values stores in a byte array to native integers.Int, uint

Static: The BitConverter type contains many static methods, and you do not need to create a new BitConverter to use these.

Static

Here: The byte array is created with 4 values. Each byte is equal to 8 bits, and four bytes is equal to 32 bits, the size of an integer.

Byte Array

ToInt32: The byte array is passed as the first parameter to the ToInt32 and ToUInt32 methods.

And: The second parameter to the methods is an offset parameter. If you are using a larger source array, you can specify the location.

C# program that converts byte array to int using System; class Program { static void Main() { // // Create an array of four bytes. // ... Then convert it into an integer and unsigned integer. // byte[] array = new byte[4]; array[0] = 1; // Lowest array[1] = 64; array[2] = 0; array[3] = 0; // Sign bit // // Use BitConverter to convert the bytes to an int and a uint. // ... The int and uint can have different values if the sign bit differs. // int result1 = BitConverter.ToInt32(array, 0); // Start at first index uint result2 = BitConverter.ToUInt32(array, 0); // First index Console.WriteLine(result1); Console.WriteLine(result2); } } Output 16385 16385
GetBytes. The BitConverter.GetBytes method group contains many static methods, differentiated only by their parameter. The GetBytes method in this example receives a value of type integer, but the other overloads can be used in the same way.

Note: The result array size varies based on the argument. This example converts an integer into a four-element byte array.

C# program that converts integer to byte array using System; class Program { static void Main() { // // Converts an integer constant into an array of bytes. // ... This example allocates a new array on the managed heap. // int value = 16385; byte[] array = BitConverter.GetBytes(value); Console.WriteLine(array[0]); Console.WriteLine(array[1]); Console.WriteLine(array[2]); Console.WriteLine(array[3]); } } Output 1 64 0 0
Notes, GetBytes. This method has several overloads, each accepting a different value type parameter. It returns a newly-allocated byte array and you can assign this array reference to a local variable.

Info: If you pass an integer type to the GetBytes method, it returns a four-element byte array.

And: If you pass a short to the GetBytes method it returns a two-element byte array.

Array Length

Tip: It is helpful to inspect the internals of the BitConverter type with the IL Disassembler tool.

IL Disassembler
ToDouble. Continuing on, this program takes an arbitrary double variable with any value in its storage location. It converts it to an array of bytes that are exactly equivalent in a logical sense to its original value.

Tip: This enables you to embed doubles in some kinds of in-memory byte arrays and files.

Main: The BitConverter.GetBytes method is invoked with one argument. The result of the GetBytes method is an eight-element byte array.

Then: The foreach-loop shows what each byte of that array is equal to when displayed in integer form.

Foreach

Convert: The final part of the program converts a byte array of eight elements back to a double value.

C# program that gets bytes from double value using System; class Program { static void Main() { // // Use any double value. // double value = 5000.1234; // // Invoke BitConverter.GetBytes to convert double to bytes. // byte[] array = BitConverter.GetBytes(value); foreach (byte element in array) { Console.WriteLine(element); } // // You can convert the bytes back to a double. // double result = BitConverter.ToDouble(array, 0); Console.WriteLine(result); } } Output 84 (Eight bytes) 116 36 151 31 136 179 64 5000.1234 (Double value)
Overloads. There are overloads available in the BitConverter.GetBytes method group in the .NET Framework. The C# compiler will automatically infer which overload you want based on the parameter type in the method call.

Note: If you want to get four bytes from a two byte value, you can always cast the parameter type to an integer before calling GetBytes.

Next: This following list shows the parameter types to GetBytes that are available in the .NET Framework.

Overload
GetBytes overload parameter types bool, Boolean char, Char double, Double short, Int16 int, Int32 long, Int64 float, Single ushort, UInt16 uint, UInt32 ulong, UInt64
Internals. The BitConverter class is available in all CLI languages, including VB.NET. The BitConverter methods use bitwise operators to read from byte arrays and return value types such as integers.

Example: The ToInt32 method uses the shift << on each byte and the bitwise "|" to combine those shifted values.

ShiftBitwise Or
The BitConverter contains a lot of special-case logic, which will reduce performance if you do not need those conditionals. The GetBytes overloads use unsafe pointer operations to improve performance.Unsafe
Discussion. BitConverter provides a higher-level way to manipulate byte representations. It is useful for manipulating binary file formats. For example, you can encode a huge amount of data into a byte array or byte stream.MemoryStream

Tip: This would improve performance and reduce footprint for fairly simple data models.

And: Byte arrays are the lowest-level representation of memory that is practical in the C# language.

IsLittleEndian. The BitConverter has a public static IsLittleEndian property. Most personal computers are little endian. This property will almost always return true in .NET programs. Endianness refers to how bits are ordered in words.Bool

Note: More information about endianness is available at Wikipedia. This next program is useless.

Endianness: Wikipedia
C# program that uses IsLittleEndian using System; class Program { static void Main() { Console.WriteLine(BitConverter.IsLittleEndian); } } Output True
Summary. The BitConverter type is used to convert data represented in a byte array to different value type representations. The BitConverter offers methods such as ToInt32 to convert arrays of bytes to an integer.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf