How to convert byte array to int in C#

2 Answers

0 votes
using System;

class Program {
    static void Main() {
        byte[] bytes = { 0, 1, 0, 0 };

        int n = BitConverter.ToInt32(bytes, 0);

        Console.WriteLine(n);
    }
}




/*
run:

256

*/

 



answered Sep 10, 2020 by avibootz
edited Sep 10, 2020 by avibootz
0 votes
using System;
 
class Program {
    static void Main() {
        byte[] bytes = { 0, 0, 2, 1 }; // 2 * 256 + 1
 
 
        if (BitConverter.IsLittleEndian)
            Array.Reverse(bytes);
            
        int n = BitConverter.ToInt32(bytes, 0);
        
        Console.WriteLine(n);
    }
}
 
 
 
 
/*
run:
 
513
 
*/

 



answered Sep 10, 2020 by avibootz

Related questions

2 answers 232 views
232 views asked Sep 10, 2020 by avibootz
1 answer 148 views
148 views asked Feb 9, 2021 by avibootz
2 answers 160 views
1 answer 195 views
3 answers 303 views
303 views asked Sep 13, 2020 by avibootz
3 answers 276 views
276 views asked Sep 5, 2019 by avibootz
...