C: Bit mask question
Karl Auer
kauer at biplane.com.au
Thu Apr 30 11:49:16 UTC 2009
On Thu, 2009-04-30 at 13:19 +0200, Bas Jacobs wrote:
> Consider a control register, which includes flags and bitfields. When
> writing such a register you often see constructions like register =
> flaga | flagb | flagc; etc. In a library those flags are then defined
> as #define flaga (1 << 6) and #define flagb (1 << 13) (for instance).
> In my library there is also a definition for a bitfield, which looks
> something like this: #define bitfieldA (0x0F << 16) for a 4bit
> bitfield located at bits 19 .. 16. Lets say that I want write 0x6 into
> this field, how do I do this (using the macro of course)?
Assuming C, you bitwise OR the desired value with the existing value,
just as you do with single-bit values.
#define bitfieldA (0x0F << 16)
#define mybits (0x06)
#define myflags (bitfieldA | mybits)
Alternatively if it is bitfieldA you want changed:
#define bitfieldA ((0x0F << 16) | 0x06)
Uncompiled, untested, but roughly like that.
Regards, K.
PS: Try not to use reserved words like "register" as variable names :-)
PPS Try to make your macro names look like macro names and not like
ordinary variables. So "FLAGA" rather than "flaga"...
PPPS: "16", "0x06" and "0x0F" are all candidates for getting the
--
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Karl Auer (kauer at biplane.com.au) +61-2-64957160 (h)
http://www.biplane.com.au/~kauer/ +61-428-957160 (mob)
GPG fingerprint: 07F3 1DF9 9D45 8BCD 7DD5 00CE 4A44 6A03 F43A 7DEF
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part
URL: <https://lists.ubuntu.com/archives/ubuntu-users/attachments/20090430/20d3e685/attachment.sig>
More information about the ubuntu-users
mailing list