How to read an integer from a byte []

I have a byte array, and I would like to read an integer from this array. How can i do this?

Something like that:

int i; tab = new byte[32]; i = readint(tab,0,3); // i = int from tab[0] to tab[3] (int = 4 bytes?) i = readint(tab,4,7); 

etc...

+8
c #
source share
4 answers
 byte[] bytes = { 0, 0, 0, 25 }; // If the system architecture is little-endian (that is, little end first), // reverse the byte array. if (BitConverter.IsLittleEndian) Array.Reverse(bytes); int i = BitConverter.ToInt32(bytes, 0); Console.WriteLine("int: {0}", i); 

Link: How to convert byte array to int

+14
source share

In addition, there is a class called Endian in the Jon Skeet miscutil library that implements conversion methods between an array of bytes and various primitive types, taking into account the statement.

For your question, usage would be something like this:

 // Input data byte[] tab = new byte[32]; // Pick the appropriate endianness Endian endian = Endian.Little; // Use the appropriate endian to convert int a = endian.ToInt32(tab, 0); int b = endian.ToInt32(tab, 4); int c = endian.ToInt32(tab, 8); int d = endian.ToInt32(tab, 16); ... 

A simplified version of the Endian class will look something like this:

 public abstract class Endian { public short ToInt16(byte[] value, int startIndex) { return unchecked((short)FromBytes(value, startIndex, 2)); } public int ToInt32(byte[] value, int startIndex) { return unchecked((int)FromBytes(value, startIndex, 4)); } public long ToInt64(byte[] value, int startIndex) { return FromBytes(value, startIndex, 8); } // This same method can be used by int16, int32 and int64. protected virtual long FromBytes(byte[] buffer, int startIndex, int len); } 

And then the FromBytes abstract method FromBytes implemented differently for each endian type.

 public class BigEndian : Endian { protected override long FromBytes(byte[] buffer, int startIndex, int len) { long ret = 0; for (int i=0; i < len; i++) { ret = unchecked((ret << 8) | buffer[startIndex+i]); } return ret; } } public class LittleEndian : Endian { protected override long FromBytes(byte[] buffer, int startIndex, int len) { long ret = 0; for (int i=0; i < len; i++) { ret = unchecked((ret << 8) | buffer[startIndex+len-1-i]); } return ret; } } 
+5
source share

You can use BitConverter.ToInt32 . Check it out .

+3
source share

If you want to do it manually, something like this should do the trick!

 byte[] data = ...; int startIndex = 0; int value = data[startIndex]; for (int i=1;i<4;i++) { value <<= 8; value |= data[i+startIndex]; } 
+2
source share

All Articles