0

I have a 3 byte Array which I need to

  • Convert each byte to Nibbles
  • Add Byte_0.Nibble_0 + Byte_0.Nibble_1 + Byte_1.Nibble_2 as WORD
  • Add Byte_1.Nibble_0 + Byte_2.Nibble_1 + Byte_2.Nibble_2 as WORD
  • Convert each WORD to Byte Array

enter image description here

Here is what I tried

 private static void GetBytesToNibbles(byte[] currentThree, out byte[] a, out byte[] b)
        {
            var firstLowerNibble = currentThree[0].GetNibble(0);
            var firstUpperNibble = currentThree[0].GetNibble(1);
            var secondLowerNibble = currentThree[1].GetNibble(0);
            var secondUpperNibble = currentThree[1].GetNibble(1);

            var thirdLowerNibble = currentThree[2].GetNibble(0);
            var thirdUpperNibble = currentThree[2].GetNibble(1);

            a= new byte[] {firstLowerNibble, firstUpperNibble, secondLowerNibble, 0x00};
            b= new byte[] {secondUpperNibble, thirdLowerNibble, thirdUpperNibble, 0x00};
        }

Get Nibble Extension:

 public static byte GetNibble<T>(this T t, int nibblePos)
            where T : struct, IConvertible
        {
            nibblePos *= 4;
            var value = t.ToInt64(CultureInfo.CurrentCulture);
            return (byte) ((value >> nibblePos) & 0xF);
        }

Am I doing it right as demonstrated in the image? If not can anyone help me with the right code?

HaBo
  • 13,999
  • 36
  • 114
  • 206
  • "Convert each WORD to Byte Array" - I'd expect `byte[2]` as result and not `byte[4]` as you have... You may want to clarify what is actual expected result. – Alexei Levenkov Jan 31 '19 at 05:47
  • @AlexeiLevenkov you are right, that is what I need to do. I need to have byte[2] but with that padded 0000. Not sure how to implement it. – HaBo Jan 31 '19 at 06:57

1 Answers1

0

This is not perfect but it will give you a 4-byte array that you should be able to split yourself.

The image is confusing because it shows the bit numbers and not example values. I think this is why you thought you needed two 4-byte arrays.

public static void Main()
{
    byte byte0 = 0x11;
    byte byte1 = 0x22;
    byte byte2 = 0x33;

    int low = BitConverter.ToInt32(new byte[]{byte0, byte1,0,0},0);
    int high = BitConverter.ToInt32(new byte[] {byte1, byte2,0,0},0);

    low = low & 0x0fff;
    high = high & 0xfff0;
    high = high << 12;
    int all = high | low;

    byte[] intBytes = BitConverter.GetBytes(all);

    for (int i = 0; i < intBytes.Length; i++)
    {
        Console.WriteLine(String.Format("{0:X2}", intBytes[i]));
    }
}

Result:

11 02 32 03

Deolus
  • 317
  • 5
  • 13