1

我正在尝试创建一个函数(C#),它将采用 2 个整数(一个值成为字节 [],一个值将数组的长度设置为)并返回一个表示该值的字节 []。现在,我有一个函数,它只返回长度为 4 的 byte[]s(我假设是 32 位)。

例如,像 InttoByteArray(0x01, 2) 这样的东西应该返回一个 {0x00, 0x01} 的字节[]。

有人对此有解决方案吗?

4

6 回答 6

4

你可以使用以下

    static public byte[] ToByteArray(object anyValue, int length)
    {
        if (length > 0)
        {
            int rawsize = Marshal.SizeOf(anyValue);
            IntPtr buffer = Marshal.AllocHGlobal(rawsize);
            Marshal.StructureToPtr(anyValue, buffer, false);
            byte[] rawdatas = new byte[rawsize * length];
            Marshal.Copy(buffer, rawdatas, (rawsize * (length - 1)), rawsize);
            Marshal.FreeHGlobal(buffer);
            return rawdatas;
        }
        return new byte[0];
    }

一些测试用例是:

    byte x = 45;
    byte[] x_bytes = ToByteArray(x, 1);

    int y = 234;
    byte[] y_bytes = ToByteArray(y, 5);

    int z = 234;
    byte[] z_bytes = ToByteArray(z, 0);

这将创建一个您传入的类型的任何大小的数组。如果您只想返回字节数组,它应该很容易更改。现在它以更通用的形式

为了在你的例子中得到你想要的,你可以这样做:

    int a = 0x01;
    byte[] a_bytes = ToByteArray(Convert.ToByte(a), 2);
于 2009-07-17T18:57:17.870 回答
2

您可以为此使用 BitConverter 实用程序类。尽管我认为它不允许您在转换 int 时指定数组的长度。但是你总是可以截断结果。

http://msdn.microsoft.com/en-us/library/de8fssa4.aspx

于 2009-07-17T17:23:36.763 回答
0

如果指定的长度小于 4,则采用您当前的算法并从数组中删除字节,或者如果它大于 4,则用零填充它。听起来你已经解决了我的问题。

于 2009-07-17T17:23:17.733 回答
0

您需要一些循环,例如:

for(int i = arrayLen - 1 ; i >= 0; i--) {
  resultArray[i] = (theInt >> (i*8)) & 0xff; 
}
于 2009-07-17T17:26:14.043 回答
0
byte[] IntToByteArray(int number, int bytes)
{
    if(bytes > 4 || bytes < 0)
    {
        throw new ArgumentOutOfRangeException("bytes");
    }
    byte[] result = new byte[bytes];
    for(int i = bytes-1; i >=0; i--)
    {
        result[i] = (number >> (8*i)) & 0xFF;
    }
    return result;
}

result它用从低到高的字节从右到左填充数组。

于 2009-07-17T17:28:16.007 回答
-2
byte byte1 = (byte)((mut & 0xFF) ^ (mut3 & 0xFF));
byte byte2 = (byte)((mut1 & 0xFF) ^ (mut2 & 0xFF));

引自

C#:无法从 ulong 转换为字节

于 2009-07-17T17:25:58.570 回答