Search code examples
c#stringtextboxarraysint32

Wrong in convert four byte to integer then display in textbox


I use array of byte and I need to convert this 4 byte to integer and display result in textbox ,the result must 320 but it display 64

byte[] bb = new byte[4] { 64, 1, 0, 0 }; 
textBox1.Text = Convert.ToInt32(bb[0]).ToString(); // display result 64 it must 320

what is wrong??


Solution

  • The method you need is BitConverter.ToInt32()

    Change the code such that:

    byte[] bb = new byte[4] { 64, 1, 0, 0 }; 
    textBox1.Text = BitConverter.ToInt32(bb, 0).ToString();
    

    Note that BitConnverter takes a byte array and a start index.

    In your example, you just have a 4 byte array. if you are going to read from a large array and convert the values one by one, make sure you pass the correct index to the ToInt32 method.