[StructLayout(LayoutKind.Explicit)]
struct MyStruct {
[FieldOffset(0)]
public byte F1;
[FieldOffset(1)]
public byte F2;
[FieldOffset(2)]
public byte F3;
[FieldOffset(3)]
public byte F4;
}

MyStruct s;
s.F1 = 0x00;
s.F2 = 0xF1;
s.F3 = 0x00;
s.F4 = 0x01;

uint p = 0x00F10001;

How can I convert MyStruct s to uint p ?
Thanks in advance.

Recommended Answers

If I see it right you can simply use a cast like p=(uint)s;

Jump to Post

All 3 Replies

If I see it right you can simply use a cast like p=(uint)s;

I did try the following:
p = (uint) s;

But it didn't work.

Instead of writing my own function, does C# provide any function in doing this?
Any help/comment will be appreciate.

He sunny1106 go white your cellar or something.
wilsoncls, indeed my cast proposal did not work but this might help it is something to acces individual bits in an integer with an indexer.

struct IntBits
    {
        private int _bits;

        public IntBits(int InitialBitValue)
        {
            _bits = InitialBitValue;
        }

        //declare indexer
        public bool this[int index]
        {
            get
            {
                return (_bits & (1 << index)) != 0;
            }
            set
            {
                if (value)
                    _bits |= (1 << index);  //set bit index 1
                else
                    _bits &= ~(1 << index); //set bit index 0           
            }
        }
    }

It is used like this
int a=12;
IntBits Mybits= new IntBits(a);

In this case Mybits[2] would be true, Mybits[1] would return false

Be a part of the DaniWeb community

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