0

I have a byte array result. I would like to convert my type called Info which are all int to the byte array but all of them are in different size.

a = 4 bytes

b = 3 bytes

c = 2 bytes

d = 1 bytes

This is the code I've tried.

private byte[] getInfoByteArray(Info data)
{
    byte[] result = new byte[10];
    BitConverter.GetBytes((data.a)).CopyTo(result, 0);
    BitConverter.GetBytes((data.b)).CopyTo(result, 4);
    BitConverter.GetBytes((data.c)).CopyTo(result, 7);
    result [9] = Convert.ToByte(data.d);

    return result;
    }

However, I found out that BitConverter.GetBytes returns 4 bytes.

Are there any general solutions that can get different size of bytes to a byte array?

2
  • int is always stored as 4 bytes. GetBytes() doesn't always only return byte arrays that are 4 long, it's only doing that because you're using the int data type. You could use this answer to calculate the minimum number of bytes needed to hold your integer values (presumable returning the 4, 3, 2, and 1 sizes as listed), then trim the result of .GetBytes() to that length before copying to your final byte array. Commented Sep 7, 2016 at 2:23
  • 1
    It's not clear why you want different byte lengths for your fields, especially if they are all actually int types. If you are sure you really only need 3, 2, or 1 byte for b, c, and d, then c and d can be short and byte, giving you exactly what you need. Your result for b depends on endianness, but you can truncate the array, e.g. Array.Copy(BitConverter.GetBytes(data.b), 0, result, 4, 3). I.e. if you don't want all the bytes, then don't copy all the bytes. Commented Sep 7, 2016 at 2:24

1 Answer 1

1

Use Array.Copy(Array, Int32, Array, Int32, Int32) method:

byte[] result = new byte[10];
Array.Copy(BitConverter.GetBytes(data.a), 0, result, 0, 4);
Array.Copy(BitConverter.GetBytes(data.b), 0, result, 4, 3);
Array.Copy(BitConverter.GetBytes(data.c), 0, result, 7, 2);
Array.Copy(BitConverter.GetBytes(data.d), 0, result, 9, 1);

This assumes little endian hardware. If your hardware is big endian, use

byte[] result = new byte[10];
Array.Copy(BitConverter.GetBytes(data.a), 0, result, 0, 4);
Array.Copy(BitConverter.GetBytes(data.b), 1, result, 4, 3);
Array.Copy(BitConverter.GetBytes(data.c), 2, result, 7, 2);
Array.Copy(BitConverter.GetBytes(data.d), 3, result, 9, 1);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.