Kosmos - 11 months ago 77

C Question

For example, I have byte = 245. I want to get any amount of subbits from it and convert it to integer. How I can do this?

For example, I need values from 2 to 5 bits or from 0 to 2, 5 to 7.

Any solution on C based language is fine.

Currently I use this function to get single bits:

`public bool GetBitFromByte(byte b, byte bit_index_0_7)`

{

var bit = (b & (1 << bit_index_0_7)) != 0;

return bit;

}

With this function I gather bools array and pass it into this junk function:

`public static byte[] GetBytesFromBits(bool[] bits)`

{

int bits_amount = bits.Length;

while (bits_amount % 8 > 0)

bits_amount++;

byte[] vals = new byte[bits_amount / 8];

for (int i = 0; i < bits.Length; i += 8)

{

byte val = 0;

for (int j = i; j < i + 8 && j < bits.Length; j++)

{

val <<= 1;

if (bits[j]) val |= 1;

}

vals[i / 8] = val;

}

return vals;

}

Thins function logic is very weird and I looking for more clear and native way.

Answer

This is called masking. You specify the bits as powers of two (e.g. in C++, `1<<i`

for bit `i`

), sum these to form the mask, then use `&`

on the original value and the mask.

Source (Stackoverflow)