1

I know I can convert a byte array to an int array with the following:

int[] bytesAsInts = yourBytes.Select(x => (int)x).ToArray();

How can I convert a byte array to an int array of a fixed size and pad the remaining with 0x00?

E.g., my byte array is 10 bytes, and I want to create an int array of length 14. The code should convert the 10 bytes of my byte array, and pad the remaining 4 with 0x00

4 Answers 4

5

Write yourself a reusable extension method that can pad a sequence:

static IEnumerable<T> AppendPadding(this IEnumerable<T> items, int totalCount, T paddingItem) {
 int count = 0;
 foreach (var item in items) {
  yield return item;
  count++;
 }

 for (int i = count; i < totalCount; i++)
  yield return paddingItem;
}

And use it like this:

int[] bytesAsInts = yourBytes.Select(x => (int)x).AppendPadding(14, 0).ToArray();

This works on any kind of sequence with a single linear pass over the sequence. It is also lazy. Abstracting away the problem of padding a sequence allows you remove the complexity of doing the padding from the main algorithm. It is now hidden in some other place nobody has to care about. Factoring out unimportant details leads to clean code because all the complexity is hidden behind a well-defined interface.

Sign up to request clarification or add additional context in comments.

Comments

1
int[] array = new int[14];
bytesAsInts.CopyTo(array, 4);

3 Comments

This is attractive (fast) but you're not doing the padding (zeroing) and fillimg the last 10 instead of the first.
Your right, but int would have defailt value 0 anyway. Or am I missing something?
@HenkHolterman tail of the "array" will filled with zeros. In a C# it is not simple to get an uninitialized array, I think…
1

Maybe not most readable, but oneliner :)

int[] bytesAsInts = yourBytes.Select(x => (int)x)
         .Concat(Enumerable.Repeat(0,14-yourBytes.Length)).ToArray();

Comments

0

@usr definitely has a great answer. Here's another way, not as robust. But explains the logic, useful for any language, implemented in its own way. Here desiredSize could be set by input.

int desiredSize = 14;
int[] myArray = new int[desiredSize ];
for(int i = 0; i < myArray.Length; i++)
{
    if(i <= yourBytes.Length)
        myArray[i] = (int)yourBytes[i];
    else
        myArray[i] = 0x00;
}

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.