将int复制到byte []的最简单方法

时间:2009-08-17 10:06:12

标签: c# bytearray

我有一个byte [],我正在遍历一个int(和其他数据)列表,我想将int复制到我的byteArray [index * 4]我该怎么做?

7 个答案:

答案 0 :(得分:20)

BitConverter很可能是你的朋友。

但是,这通常会返回 new 字节数组。它也不允许您指定字节顺序。我在MiscUtil中有EndianBitConverter类,它有通过将数据直接复制到现有字节数组来转换基元类型的方法。

例如:

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

答案 1 :(得分:8)

BinaryWriter如何做到这一点:

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

(显然这会将int复制到数组的前4个字节中)

答案 2 :(得分:6)

有许多不同的方法可以做到这一点,但为了使它更好,让我们使用c#:extensions的新功能。

32位变量的整数需要4个字节,因此它将占用byte []中的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);

答案 3 :(得分:6)

我将尝试总结一些以前的答案来制作新的东西

第1步。正如Jon Skeet之前所说:

  

BitConverter很可能是你的朋友。

     

但是,这通常会返回 new 字节数组。

第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;
}

第3步。使用想象力并更改第2步代码中的几行,以便将数据保存到现有数组中:

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;
}

答案 4 :(得分:1)

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

在两个阵列之间复制数据。最后一个参数是要以字节为单位的数据量。

答案 5 :(得分:0)

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;
}

答案 6 :(得分:0)

概括亚行的优秀答案:

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));
        }
    }
}