3

Quite often when using hardware interfaces you'll have to set groups of bits or set them without changing the rest of the bits. The interface description says something like: you get a System.UINT32, bit 0 is set if available; bits 1..7 mean the minimum value; bits 8..14 is the maximum value; bits 15..17 is the threshold, etc. I have to do this for a lot of values, each with their own start and stop bits.

That's why I'd like to create a class that can convert the values (start bit; stop bit; raw UINT32 value) into the value it represents, and back.

So something like:

class RawParameterInterpreter
{
    public int StartBit {get; set;}    // counting from 0..31
    public int StopBit {get; set;}     // counting from 0..31

    Uint32 ExtractParameterValue(Uint32 rawValue);
    Uint32 InsertParameterValueToRawValue(Uint32 parameterValue,
        Uint32 rawValue);
}

I understand the part with handling the bits:

// example bits 4..7:
extract parameter from raw value: (rawvalue & 0x000000F0) >> startbit;
insert parameter into raw: (parameter << startbit) | (rawValue & 0xFFFFFF0F)

The problem is, how to initialize the 0x000000F0 and 0xFFFFFF0F from values startBit and endBit? Is there a general method to calculate these values?

I would use something like this

Uint32 bitPattern = 0;
for (int bitNr = startBit; bitNr <= stopBit; ++bitNr)
{
    bitPattern = bitPattern << 2 + 1;
}
bitPattern = bitPattern << startBit;

I know the class System.Collections.BitArray. This would make it even easier to set the bits, but how to convert the BitArray back to Uint32?

So question: what is the best method for this?

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
  • Frankly, I'd just stick with the `&` / `|` / `~` / `>>` / `<<`; anything like `BitArray` is an unnecessary overhead. – Marc Gravell Jun 30 '14 at 08:07
  • 1
    It all depends on what you want to do. – Jodrell Jun 30 '14 at 08:08
  • People use CopyTo it seems ... have you read http://stackoverflow.com/questions/9697623/bitarray-to-integer-issue ? or http://stackoverflow.com/questions/5283180/how-i-can-convert-bitarray-to-single-int ? – Paul Zahra Jun 30 '14 at 08:09
  • possible duplicate of [C: Most efficient way to set all bits in a range within a variable](http://stackoverflow.com/questions/22662807/c-most-efficient-way-to-set-all-bits-in-a-range-within-a-variable) – harold Jun 30 '14 at 08:14
  • ^ that's if you want to do it without things being constants. Constants are better though. – harold Jun 30 '14 at 08:20

1 Answers1

2

Well, your question is very general but,

You could use an enum with a Flags attribute.

[Flags]
public enum BitPattern
{
    Start = 1,
    Stop = 1 << 31
}
Community
  • 1
  • 1
Jodrell
  • 34,946
  • 5
  • 87
  • 124