I have a byte[] and i am iterating through a list of ints(and other data) and i want to copy the int to my byteArray[index*4] How do i do this?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
There are many different ways to do it, but to make it nicer, lets use a new feature of c#: extensions.
An integer of the 32 bit variety takes 4 bytes, so it will occupy 4 spots in the byte[]. How do you break an integer in its 4 constituent bytes? You can do it using the bit manipulation operator >>. That operator shifts the bits in the integer by the specified number of bits. For example:
Since a byte is 8 bits if we shift the integer by 8 bits we will have the new second byte value of the integer in the right-most bits position
Notice how the second byte is not the first byte and the rest of the bits have been replaced by 0.
We can use this trick to move the bytes into the first position, then force a cast to byte, which will discard the 3 other bytes and will leave us the last bytes value:
So, using this technique for the 4 bytes will give us access to each one and we will copy them in a destination array that was passed to our new CopyToByteArray method:
Note that we could have copied the bytes in reverse order, that is up to your implementation.
The extension function will allow you to access the new function as a member of the integer class:
Buffer.BlockCopy(intArray, 0, byteArray, 0, 4*intArray.Length)
Copies data between two arrays. The last argument is the amount of data to copy in bytes.
Do it how the BinaryWriter does it:
(obviously this will copy the int into the first 4 bytes of the array)
I'll try to summarize some of the previous answers to make something new
Step 1. As Jon Skeet said before:
Step 2. You can find the source code of BitConverter.GetBytes(int value) method:
Step 3. Using imagination and changing a few lines in the code from step 2 so it could save the data to an existing array:
BitConverter
is quite possibly your friend.However, that generally returns you a new byte array. It also doesn't let you specify endianness. I have the
EndianBitConverter
class in MiscUtil which has methods to convert primitive types by copying the data directly into an existing byte array.For instance: