0

there is array of bits

BitArray bits = new BitArray(17);

i want to take first 13 bit and convert into 13bits signed integer and remainder in bits array 4 bits convert into 4 bits integer. How can I do it in C#?

Zong
  • 6,160
  • 5
  • 32
  • 46
user2922938
  • 227
  • 5
  • 13

1 Answers1

1

Assuming your bits are stored LSB first (e.g., left most in the BitArray), you can do something like this (borrowing off of this post: How can I convert BitArray to single int?).

int[] arr = new int[1];
bits.CopyTo(arr, 0);                 // assume that bits are stored LSB first
int first13Bits = arr[0] >> 4;       // shift off last 4 bits to leave top 13
int last4Bits = 0x0000000F & arr[0]; // mask off top 28 bits to leave bottom 4

Note that first13Bits should be signed, but last4Bits will not be signed here (since the top bits are masked off). If your bits are stored MSB first you will need to reverse the bits in the BitArray before you convert them (as CopyTo seems to assume they're stored LSB first).

Community
  • 1
  • 1
mattnedrich
  • 7,577
  • 9
  • 39
  • 45