tags:

views:

147

answers:

1

What I mean is: Imagine we have a 8 byte variable that has a high value and low value. I can make one pointer point to the upper 4 bytes and other point to the lower 4 bytes, and set/retrieve their values without problems. Now, is there a way to get/set values for anything smaller than a byte? If instead of dividing it in two 4 bytes "variables", I'd want to consider eight 1 byte variables I could use a bool, but there is no defined smaller variable in c#. Would it possible to divide it to 16 just with pointers? Or even in 32, 64? It wouldn't right?

This is a pretty academic question, I know this can be achieved otherwise with bitshiffting, unions(Struct.Explicit), etc. Thanks!

+2  A: 

No, C# does not support bit fields and a byte is the minimum amount of addressable memory. You can manually provide properties that change one or several specific bits but you have to provide packing/unpacking logic yourself:

public bool Bit5 {
    get { return (field & 32) != 0; }
    set { if (value) field |= 32; else field &= ~32; }
}

By the way, I don't know how you achieve it using LayoutKind.Explicit as the minimum FieldOffset you can specify is one byte.

As a side note, even C++ that can do this with bit fields will just hide the bitwise tricks and makes the compiler do it instead of you. There's no way you could grab something less than a byte from memory to a register, at least on x86 architecture.

Mehrdad Afshari
devoured elysium
`32` is `2^5 = 100000`. If the result of bitwise and of field and 32 is zero, bit 5 has to be zero. Otherwise, it has to be 1.
Mehrdad Afshari
Ah, yes. That was obvious. Thanks!
devoured elysium
In fact, even on x86, you're always fetching at least 32 bits of memory to a register. The "load byte" CISC instructions simply translate to a load-word followed by a mask in the actual trace.
Crashworks
@Mehdrad: it better style to express bitmasks in hexadecimal; e.g. 0x20 instead of 32. Lots of folks cannot do hex <-> decimal conversions in their heads.
Stephen C
@Stephen: I wanted to write it as `(1 << 5)`. I thought it would just complicate things. Anyway, after all, if you are trying to do something like this, you should be comfortable with bitwise operations.
Mehrdad Afshari