1

I need to write a 8 bit packet, that includes 3 ints, in this division:

int1 = 1 bit
int2 = 1 bit
int3 = 6 bit

I don't know how to do that. I can write some 4 bytes packets, using this function which work for us:

buffer.AddRange(BitConverter.GetBytes(_value));

But I need help in writing a 8 bit packet divided in many ints (or bit elements). I have read about BitArray, but I really don't know how to use it. I have written some code, but don't know if it really is going to work:

bool playback = false;
bool extExerciseNum = false;
BitArray byte4 = new BitArray(2);
byte4.Set(0, playback);
byte4.Set(1, extExerciseNum);

Here I pretend to create a BitArray with the first 2 individual ints.

int exerciseNumber = 23;
BitArray b = new BitArray(new int[] { exerciseNumber });
int[] bits = b.Cast<bool>().Select(bit => bit ? 1 : 0).ToArray();

And here, I pretend to write a 6 bit length BitArray (I don't understand it properly, by the way).

Anyone can help me how to write this package properly? Thank you so much!!

4
  • Just shift them in. Which order do they need to be in? Commented Nov 21, 2020 at 9:19
  • That order: 1 bit first; then another 1 bit; and finally, at the end, the 6 bits int. Commented Nov 21, 2020 at 10:09
  • Within a byte, "first" does not make sense. The question from @TheGeneral was if int1 should occupy the most signitficant bit (MSB) or the least significant bit (LSB) Commented Nov 21, 2020 at 10:44
  • Yes sorry, int1 occupy the MSB Commented Nov 21, 2020 at 10:57

1 Answer 1

0

Assuming int1 should occupy the most signitficant bit (MSB), use bit shift and or to produce the 8 bit value:

byte result = (byte)((int1 << 7) | (int2 << 6) | int3);

(no range check included). For the other bit order (int1 should occupy the least signitficant bit):

byte result = (byte)(int1 | (int2 << 1) | (int3 << 2));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! So maybe, the final code will look like this (using the ints: 1, 0 and 23)?: byte result = (byte)((1 << 7) | (0<< 6) | 23);

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.