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 Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in classes and tagged , , , , , , , , , . Bookmark the permalink.

2 Responses to Convert an array of bytes into an integer and back in C#

  1. using CollectionWorldWide;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.InteropServices;
    namespace CollectionWorldWide
        public class Country
            public string  Name { get; }
            public string  Code { get; }
            public string  Region { get; }
            public int Population { get; }
            public Country (string name,string code, string region,int population)
                Name = name;
                Code = code;
                Region = region;
                Population = population;
        public class CsvReader
            private string _filePath;
            public CsvReader(string filePath)
                _filePath = filePath;
                public List ReadAllCountries();
                    var Countries = new List()
                    using (var streamReader = new StreamReader(_filePath))
                        string csvLine;
                        while ((csvLine= StreamReader .ReadLine())!=null );
                                Country country=ReadCountriesFromCsvFile(csvLine)
                            return Countries;
                    private Country ReadCountriesFromCsvFile(string csvLine)
                        var parts =csvLine.Split( ',');
                         string name;
                            string code;
                            string region;
                            string popText;
                        switch (parts.Length)
                            case 4:
                                name = parts[0];
                                code = parts[1];
                                region = parts[2];
                                popText = (parts[3]);
                            case 5:
                                 name = parts[0] + "," + parts[1];
                                name = name.Replace("\"", null).Trim();
                                code = parts[2];
                                region = parts[3];
                                popText = (parts[4]);
                            throw new System.Exception("can't the parse"); 
                        int.TryParse(popText, out int Population);
                        return new Country(name, code, region, Population);
       class Program
            static void Main(string[] args)
                string filePath = @"C:\pop of Largest final.Csv";
                CsvReader csvReader = new CsvReader(filePath);
                var readCountriesFromCsvReader = csvReader.ReadAllCountries();
                foreach (var Country in readCountriesFromCsvReader)
                    Console.WriteLine($"{Country :Population, 15}{Country :Name}");

    please boss .you are understanding this code expleain why code error.

Comments are closed.