简体   繁体   中英

How to get subbits from byte as separate integer value?

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.

This is called masking. You specify the bits as powers of two (eg in C++, 1<<i for bit i ), sum these to form the mask, then use & on the original value and the mask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM