Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Converting byte array to int array

Status
Not open for further replies.

jmofthenorth

Technical User
May 8, 2007
7
US
Hi.
I have a Byte array that I'd like to convert to long ints. Is there a quick way of doing this.
essentially I'd like to take bytes: bytearray[0], bytearray[1], bytearray[2], bytearray[3] and combine them to form one int32 (here bytearray[3] has the lsb and [0] the msb).
There must be a method already implemented in C# to do this...
jm
 
That linked helped, but it was confusing. What I was looking for, for anyone who's interested is the method BitConverter.ToInt(); which allows one to select a subsection from a byte array and the convert it to an Int.
 
I’m just a novice C# programmer …

byte[] dog= {2,3,4,5,6,7};

long result= dog[0];
result = ( result<<8 ) + dog[1];
result = ( result<<8 ) + dog[2];
result = ( result<<8 ) + dog[3];

unsafe{
byte* dogArray= (byte*)&result;
byte a= dogArray[0];
byte b= dogArray[1];
byte c= dogArray[2];
byte d= dogArray[3];
}

First I have created a byte array “dog”.
I have constructed a long from the first four bytes of dog in a safe manner. Note that byte zero is the most significant.

Now, since I wish to be daring and use pointers, I need an “unsafe” code block. I also need to set the “/unsafe” switch in the compiler (see compiler documentation).

Now I can extract the byte values from the long. It turns out that they are saved least significant byte first.

Translating a byte array into a long array is not smart because a long array has to be word aligned in memory. You need to get the long array first, and copy the bytes into it that way.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top