skatamatic 371 Practically a Posting Shark

I am trying to remember a bit of bitwise math to deal with some CAN bus stuff in c#. Basically, I am trying to create a class that takes in an integer that represents an identifier portion of a CAN frame. They look like this:

Priority - 3 bits
EXT Data Page - 1 bit
Data page -1 bit
PDU Format - 8 bits
PDU Specific - 8 bits
Source Address - 8 bits

I want to pass a single 32 bit integer containing all these fields into the class. The class will have properties for each field type, the get will apply a mask to the integer then shift the masked result all the way to the right to get an actual numeric value for the field. The set will do the opposite. It will create a mask to zero out the old value in the given field, create the bits that represent the new value, shift these all into their respective offset position, then logically or the 2 to set the field.

2 Questions - does this sound like a good way of doing this? And does this code look like it will work? (it's been a while since I've worked directly with bits)

static class BitHelpers
{
    public static Int32 GetBitsValue(Int32 original, int offset, int size)
    {
        return (original >> offset) & MakeZeroesMask(size, 0);
    }

    public static Int32 SetBitsValue(Int32 original, int offset, int size, int value)
    {
        if (value >= (int.MaxValue >> (32 - (size + 1))))
            throw new InvalidOperationException("Value cannot exceed 2^size");
        return (original & MakeOnesMask(size, offset)) | (value << offset);
    }

    public static Int32 MakeOnesMask(int size, int offset)
    {
        int ibase = int.MaxValue;
        int ibit = 1 << offset;
        for (int i = 0; i < size; i++)
            ibase -= ibit << i;
        return ibase;
    }

    public static Int32 MakeZeroesMask(int size, int offset)
    {
        int ibase = 0;
        int ibit = 1 << offset;
        for (int i = 0; i < size; i++)
            ibase += ibit << i;
        return ibase;
    }
}

And this is an example implementation in the class:

    byte Priority 
    {
        get
        {
            return (byte)BitHelpers.GetBitsValue(Identifier, 0, 3);
        }

        set
        {
            Identifier = SetBitsValue(Identifier, 0, 3, value);
        }
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.