[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Convert an array of bytes into an integer and back in C#

[Convert an array of bytes into an integer and back in C#]

The BitConverter class provides static methods that let you convert various data types to and from arrays of bytes. (I suppose it might have made more sense to call it the ByteConverter class.) You can use those methods to convert data that you load from files and other sources that has been stored in ways that make it hard for you to read the value directly into the appropriate types.

This example uses the following code to convert some bytes into an integer and back. Most of the code is used to display the bytes. The calls to BitConverter methods, which are quite simple, are highlighted in bold.

private void Form1_Load(object sender, EventArgs e) { // Initialize a byte array. byte[] bytes = { 121, 222, 111, 212 }; string txt = ""; for (int i = 0; i < bytes.Length; i++) { txt += bytes[i].ToString() + " "; } txtBytes1.Text = txt; // Convert to an integer. int int_value = BitConverter.ToInt32(bytes, 0); txtInteger.Text = int_value.ToString(); // Convert back to a byte array. byte[] new_bytes = BitConverter.GetBytes(int_value); txt = ""; for (int i = 0; i < new_bytes.Length; i++) { txt += new_bytes[i].ToString() + " "; } txtBytes2.Text = txt; txtBytes1.Select(0, 0); }

The code initializes an array of bytes to an arbitrary value. It then uses BitConverter.ToInt32 to convert those bytes into a 32-bit integer. Finally it uses BitConverter.GetBytes to convert the integer back into an array of bytes.

The BitConverter class makes all of this relatively straightforward. It gets a little more confusing if the data you are working with came from another computer that stores an integer's bytes in a different order. For example, if you are working on a "big endian" system but the data was generated on a "little endian" system or vice versa. In that case, you may need to rearrange the bytes yourself before converting them into integers. See the online help for BitConverter Class for more information.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.