Is there a way of converting a int array into a byte array. In C you could build a union an just fill the int array. I also need to go from a byte array to a int array after transmission.
Loading
Is there a way of converting a int array into a byte array. In C you could build a union an just fill the int array. I also need to go from a byte array to a int array after transmission.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
gordonPosted Aug 12, 2007, 10:06 PM
your right, but the values in the array span byte boundries i.e. the fist value is contained in the first 9 bits. So it eisier to take in multiple bytes and shift left and right to get the value. Thanks again.
AlanPosted Aug 12, 2007, 3:00 PM
Convert.ToInt32(byteValue) is equivalent to casting the byte value to an int.
So, if you have a byte with a value of 32, it just 'widens' it to a 4 byte Int32 containing the same value.
gordonPosted Aug 12, 2007, 2:28 PM
AlanPosted Aug 12, 2007, 11:47 AM
You can use:
int i = BitConverter.ToInt32(ba, 2);
which takes the 4 bytes of the byte array starting at index 2 (zero-based) and converts them to an int.
gordonPosted Aug 12, 2007, 11:05 AM
AlanPosted Aug 12, 2007, 10:27 AM
Sorry, I forgot about that one :)
int[] ia = new int[ba.Length / 4];
for(int i = 0; i < ia.Length; i++)
{
int j = 4 * i;
ia[i] = ((int)ba[j+3] << 24) + ((int)ba[j+2] << 16) + ((int)ba[j+1] << 8) + ((int)ba[j]);
}
gordonPosted Aug 12, 2007, 10:08 AM
AlanPosted Aug 12, 2007, 10:00 AM
In C#, I think most people would just do something like this:
int[] ia = new int[someSize];
// code to initialize ia
byte[] ba = new byte[4 * someSize];
for(int i = 0; i < ia.Length ; i++)
{
int j = 4 * i;
ba[j] = (byte)(ia[i] & 0xFF);
ba[j+1] = (byte)(ia[i] >> 8 & 0xFF);
ba[j+2] = (byte)(ia[i] >>16 & 0xFF);
ba[j+3] = (byte)(ia[i] >> 24 & 0xFF);
}
You can also use the BitConverter.GetBytes(someInt) method to get the byte representation of a single integer though using this class isn't as fast as bit arithmetic.
Although it's possible to simulate unions, you can't overlap reference types within them which, of course, is what arrays are in .NET. You might be able to do something using pointers in 'unsafe' code but I doubt whether it would be much quicker than the above.