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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
AlanRank #669 · 3.6K reputationPosted Aug 12, 2007, 6:00 AM EDT
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.
gordon47 reputationPosted Aug 12, 2007, 6:08 AM EDT
AlanRank #669 · 3.6K reputationPosted Aug 12, 2007, 6:27 AM EDT
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]);
}
gordon47 reputationPosted Aug 12, 2007, 7:05 AM EDT
AlanRank #669 · 3.6K reputationPosted Aug 12, 2007, 7:47 AM EDT
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.
gordon47 reputationPosted Aug 12, 2007, 10:28 AM EDT
AlanRank #669 · 3.6K reputationPosted Aug 12, 2007, 11:00 AM EDT
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.
gordon47 reputationPosted Aug 12, 2007, 6:06 PM EDT
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.