tags:

views:

74

answers:

2

So Say I have an array of bytes that is 16 long, with each 8 bits representing my data and an array that is 8 long with each 4 bits (so 2 per byte) representing my data.

If I wanted to loop over these and get the values, what would be the easiest way of doing so?

My poor attempt would be something like this, but this doesn't appear to be working as I expect.

for(int i = 0; i < bigByteArray.Length; i++) 
{
    byte BigByteInfo = bigByteArray[i];
    byte SmallByteInfo;
    if(i % 2 == 0)
    {
        SmallByteInfo = smallByteArray[i / 2] % 16;
    }
    else
    {
        SmallByteInfo = smallByteArray[i / 2] / 16;
    }

    //Use of data Here.
}
+1  A: 

If I understand right (bigByteArray is 16 long, smallByteArray is 8 long, packed):

for(int i = 0; i < bigByteArray.Length; i++)
{
    bigByteArray[i] = (byte)((smallByteArray[i / 2] >> (i % 2 == 0 ? 4 : 0)) & 0xF);
}
Matthew Flaschen
@matthew: your onelinre doesn't do anything notably different than his code snippet which looks on first sight good as well. It looks like his expectation of what should happen is different than the actual output
Toad
@Toad, they're similar. However, his won't compile for at least one reason (missing a conversion to byte). The above is tested.
Matthew Flaschen
Toad
@Toad, I prefer `% 2` when I'm checking whether I'm on an even or odd iteration. However, I don't think there's much difference here in readability or performance.
Matthew Flaschen
Yeah I was converting to byte in my actual program, didn't include it in my example sorry :P. As it turns out I was getting the right results, I'm just an idiot. Thanks for your attempts to help :) Hope you don't mind me accepting the other answer (as I actually implemented a class like his anyway) even though it wasn't really the answer.
Blam
+1  A: 

you can use this class as helper class

public class FoutBitsArrayEnumerator : IEnumeable<byte>
{
  FoutBitsArrayEnumerator(byte[] array)
  {
    this.array = array;
  }
  public IEnumerator<byte> GetEnumerator
  {
    foreach (byte i in array)
    {
        yield return i & 15;
        yield return (i >> 4) & 15;
    }
  }

  byte[] array;
}
Itay
Won't compile for the same reason as the OP; you're missing a conversion to byte. You also have a few typos (IEnumeable, missing method parentheses, etc.)
Matthew Flaschen
What i meant was to give him the direction not a compilable solution.
Itay
I actually implemented a solution like this now, it's a lot cleaner to read, thanks. Unfortunately my problem didn't lie in reading the data incorrectly, it was my idiocy in checking if the data was right :P
Blam