The easiest way to copy int to byte []

I have a byte [], and I repeat the list of ints (and other data), and I want to copy the int to my byteArray [index * 4]. How to do it?

+5
source share
7 answers

BitConverter quite possibly your friend.

However, this usually returns you a new byte array. It also does not allow you to specify an entity. I have a class EndianBitConverterin MiscUtil that has methods for converting primitive types by copying data directly to an existing byte array.

For example:

// Copy the bytes from the integer "value" into a byte array
// (buffer) starting at index 5
EndianBitConverter.Little.CopyBytes(value, buffer, 5);
+18
source

Do it the way BinaryWriter does it:

buffer[0] = (byte) value;
buffer[1] = (byte) (value >> 8);
buffer[2] = (byte) (value >> 0x10);
buffer[3] = (byte) (value >> 0x18);

(obviously, this will copy int into the first 4 bytes of the array)

+8

, , #: extensions.

32- 4 , 4 []. ? , β†’ . . :

integer = 10399
binary = 00101000 10011111
10399 >> 1 == 0010100 01001111 each bit shifted by 1

8 , 8 ,

10399 >> 8 = 00000000 00101000

, , 0.

, , , 3 :

(byte)(10399 >> 8) == 0010100

, 4 , , , CopyToByteArray:

public static class Int32Extension
{
    public static void CopyToByteArray(this int source, byte[] destination, int offset)
    {
        if (destination == null)
            throw new ArgumentException("Destination array cannot be null");

        // check if there is enough space for all the 4 bytes we will copy
        if (destination.Length < offset + 4)
            throw new ArgumentException("Not enough room in the destination array");

        destination[offset] = (byte)(source >> 24); // fourth byte
        destination[offset+1] = (byte)(source >> 16); // third byte
        destination[offset+2] = (byte)(source >> 8 ); // second byte
        destination[offset+3] = (byte)source; // last byte is already in proper position
    }
}

, , .

:

int something = 20;
byte[] array = new byte[4];
something.CopyToByteArray(array,0);
+6

, -

1. :

BitConverter , .

.

2. BitConverter.GetBytes(int value):

public static unsafe byte[] GetBytes(int value)
{
    byte[] numArray = new byte[4];
    fixed (byte* numPtr = numArray)
        *(int*) numPtr = value;
    return numArray;
}

Step 3. Using imagination and changing several lines in the code from step 2, so that it can save data in an existing array:

public static unsafe byte[] GetBytes(int value, int buffer[], int offset)
{
    // Here should be a range check. For example:
    // if (offset > buffer.Length + sizeof(int)) throw new IndexOutOfRangeException();

    fixed (byte* numPtr = &buffer[offset])
        *(int*) numPtr = value;
}
+6
source

Buffer.BlockCopy (intArray, 0, byteArray, 0, 4 * intArray.Length)

Copies data between two arrays. The final argument is the amount of data to copy in bytes.

+1
source
byte[] bytes = new byte[listOfInts.Count * sizeof(int)];
int pos = 0;
foreach(int i in listOfInts)
{
    byte[] b = BitConverter.GetBytes(i);
    b.CopyTo(bytes, pos);
    pos += b.Length;
}
0
source

ADB summary response:

public static class Int32Extension
{

    /// <summary>
    /// Copies an int to a byte array: Byte order and sift order are inverted.
    /// </summary>
    /// <param name="source">The integer to convert.</param>
    /// <param name="destination">An arbitrary array of bytes.</param>
    /// <param name="offset">Offset into the desination array.</param>
    public static void CopyToByteArray(this int source, byte[] destination, int offset)
    {
        if (destination == null)
            throw new ArgumentException("Destination array cannot be null");

        // check if there is enough space for all the 4 bytes we will copy
        if (destination.Length < offset + sizeof(int))
            throw new ArgumentException("Not enough room in the destination array");

        for (int i = 0, j = sizeof(int) - 1; i < sizeof(int); i++, --j) {
            destination[offset + i] = (byte) (source >> (8 * j));
        }
    }

    /// <summary>
    /// Copies an int to a to byte array Little Endian: Byte order and sift order are the same.
    /// </summary>
    /// <param name="source">The integer to convert.</param>
    /// <param name="destination">An arbitrary array of bytes.</param>
    /// <param name="offset">Offset into the desination array.</param>
    public static void CopyToByteArrayLE(this int source, byte[] destination, int offset)
    {
        if (destination == null)
            throw new ArgumentException("Destination array cannot be null");

        // check if there is enough space for all the 4 bytes we will copy
        if (destination.Length < offset + sizeof(int))
            throw new ArgumentException("Not enough room in the destination array");

        for (int i = 0, j = 0; i < sizeof(int); i++, j++) {
            destination[offset + i] = (byte) (source >> (8 * j));
        }
    }
}
0
source

All Articles