views:

258

answers:

6

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?

A: 

Take your current algorithm and chop off bytes from the array if the length specified is less than 4, or pad it with zeroes if it's more than 4. Sounds like you already have it solved to me.

Welbog
+2  A: 

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

Spencer Ruport
A: 
byte byte1 = (byte)((mut & 0xFF) ^ (mut3 & 0xFF));
byte byte2 = (byte)((mut1 & 0xFF) ^ (mut2 & 0xFF));

quoted from

http://stackoverflow.com/questions/685738/c-cannot-convert-from-ulong-to-byte

CodeToGlory
Doesn't solve the issue. Was supposed to work for an arbitrary number of bytes requested, not just two.
Martinho Fernandes
A: 

You'd want some loop like:

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

Martinho Fernandes
+2  A: 

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