Use the BitConverter class to 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 byte arrays. (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 byte array values. 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. 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 and simple. It gets a little more confusing if the data you are working with came from another computer that stores the bytes in an integer 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.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.