简体   繁体   中英

Convert an integer to a byte[] of specific length

I'm trying to create a function (C#) that will take 2 integers (a value to become a byte[], a value to set the length of the array to) and return a byte[] representing the value. Right now, I have a function which only returns byte[]s of a length of 4 (I'm presuming 32-bit).

For instance, something like InttoByteArray(0x01, 2) should return a byte[] of {0x00, 0x01}.

Does anyone have a solution to this?

You could use the following

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

Some test cases are:

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

This will create an array of whatever size the type is that you pass in. If you want to only return byte arrays, it should be pretty easy to change. Right now its in a more generic form

To get what you want in your example you could do this:

    int a = 0x01;
    byte[] a_bytes = ToByteArray(Convert.ToByte(a), 2);

You can use the BitConverter utility class for this. Though I don't think it allows you to specify the length of the array when you're converting an int. But you can always truncate the result.

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

如果指定的长度小于4,请采用当前算法并从数组中截断字节;如​​果大于4,则用零填充。听起来像您已经对我解决了。

You'd want some loop like:

for(int i = arrayLen - 1 ; i >= 0; i--) {
  resultArray[i] = (theInt >> (i*8)) & 0xff; 
}
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;
}

It fills the result array from right to left with the the bytes from less to most significant.

 byte byte1 = (byte)((mut & 0xFF) ^ (mut3 & 0xFF)); byte byte2 = (byte)((mut1 & 0xFF) ^ (mut2 & 0xFF)); 

quoted from

C#: Cannot convert from ulong to byte

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM