I'm learning about bit-flags. I already know how they work and how they are defined in a struct. However, I'm unsure if they can be defined in a #define preprocessor directive like this:
#define FLAG_FAILED:1
Is this preprocessor define directive the as a struct bit-flag definition?
PS: I've already come across this related question but it didn't answer my question: #defined bitflags and enums - peaceful coexistence in "c". Also, if you can point me towards some information regarding preprocessor directives, I would appreciate that.
Any #define that you want to use to inject bitflags into a struct must take the form:
#define IDENTIFIER SUBSTITUTED_CODE
In your postulated use...
#define FLAG_FAILED:1
The identifier contains the colon, which makes it invalid.
You could do something like this:
#define FLAG_FAILED int flag_failed :1
struct X
{
char a;
FLAG_FAILED;
int b;
...
};
It's not clear why you're considering using a define for the bit field anyway. If you just want to be able to vary the field length, then:
#define FLAG_FAILED_BITS 1
struct X
{
unsigned flag_failed :FLAG_FAILED_BITS;
};
...or...
#define FLAG_FAILED_BITS :1
struct X
{
unsigned flag_failed FLAG_FAILED_BITS;
};
#define FLAG_FAILED:1 is not really a bit flag in the sense that what most people know as a "bit flag". It's also bad syntax.
Bit flags typically are defined so that you have a type and you turn "on" bits by "setting" them. You turn them "off" by "clearing" the flag. To compare if the bit flag is on, you use what is called the bitwise operator AND (e.g. &).
So your BIT0 (e.g. 2^0) would be defined as BIT0 = 0x00000001 and BIT1 (e.g. 2^1) as BIT1 = 0x00000002. If you wanted to stick with define you could do it this way with setting and clearing:
#ifndef setBit
#define setBit(word, mask) word |= mask
#endif
#ifndef clrBit
#define clrBit(word, mask) word &= ~mask
#endif
or as a template
template<typename T>
inline T& setBit(T& word, T mask) { return word |= mask; }
template<typename T>
inline T& clrBit(T& word, T mask) { return word &= ~mask; }
If you want to set the bit, so to speak, you could have a state set as follows:
setBit(SystemState, SYSTEM_ONLINE);
or
setBit(SystemState, <insert type here>SYSTEM_ONLINE);
clearing would be the same just replace setBit with clrBit.
To compare, just do this:
if (SystemState & SYSTEM_ONLINE) { ... // do some processing
}
if this is in a struct then, reference the struct.
A form to define bitwise values with #define macros is:
#define BIT_ONE static_cast<int>( 1 << 0 )
#define BIT_TWO static_cast<int>( 1 << 1 )
#define BIT_THREE static_cast<int>( 1 << 2 )
Related
The issue
In a low level bare-metal embedded context, I would like to create a blank space in the memory, within a C++ structure and without any name, to forbid the user to access such memory location.
Right now, I have achieved it by putting an ugly uint32_t :96; bitfield which will conveniently take the place of three words, but it will raise a warning from GCC (Bitfield too large to fit in uint32_t), which is pretty legitimate.
While it works fine, it is not very clean when you want to distribute a library with several hundreds of those warnings...
How do I do that properly?
Why is there an issue in the first place?
The project I'm working on consists of defining the memory structure of different peripherals of a whole microcontroller line (STMicroelectronics STM32). To do so, the result is a class which contains a union of several structures which define all registers, depending on the targeted microcontroller.
One simple example for a pretty simple peripheral is the following: a General Purpose Input/Output (GPIO)
union
{
struct
{
GPIO_MAP0_MODER;
GPIO_MAP0_OTYPER;
GPIO_MAP0_OSPEEDR;
GPIO_MAP0_PUPDR;
GPIO_MAP0_IDR;
GPIO_MAP0_ODR;
GPIO_MAP0_BSRR;
GPIO_MAP0_LCKR;
GPIO_MAP0_AFR;
GPIO_MAP0_BRR;
GPIO_MAP0_ASCR;
};
struct
{
GPIO_MAP1_CRL;
GPIO_MAP1_CRH;
GPIO_MAP1_IDR;
GPIO_MAP1_ODR;
GPIO_MAP1_BSRR;
GPIO_MAP1_BRR;
GPIO_MAP1_LCKR;
uint32_t :32;
GPIO_MAP1_AFRL;
GPIO_MAP1_AFRH;
uint32_t :64;
};
struct
{
uint32_t :192;
GPIO_MAP2_BSRRL;
GPIO_MAP2_BSRRH;
uint32_t :160;
};
};
Where all GPIO_MAPx_YYY is a macro, defined either as uint32_t :32 or the register type (a dedicated structure).
Here you see the uint32_t :192; which works well, but it triggers a warning.
What I've considered so far:
I might have replaced it by several uint32_t :32; (6 here), but I have some extreme cases where I have uint32_t :1344; (42) (among others). So I would rather not add about one hundred lines on top of 8k others, even though the structure generation is scripted.
The exact warning message is something like:
width of 'sool::ll::GPIO::<anonymous union>::<anonymous struct>::<anonymous>' exceeds its type (I just love how shady it is).
I would rather not solve this by simply removing the warning, but the use of
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-WTheRightFlag"
/* My code */
#pragma GCC diagnostic pop
may be a solution... if I find TheRightFlag. However, as pointed out in this thread, gcc/cp/class.c with this sad code part:
warning_at (DECL_SOURCE_LOCATION (field), 0,
"width of %qD exceeds its type", field);
Which tells us that there is no -Wxxx flag to remove this warning...
How about a C++-ish way?
namespace GPIO {
static volatile uint32_t &MAP0_MODER = *reinterpret_cast<uint32_t*>(0x4000);
static volatile uint32_t &MAP0_OTYPER = *reinterpret_cast<uint32_t*>(0x4004);
}
int main() {
GPIO::MAP0_MODER = 42;
}
You get autocompletion because of the GPIO namespace, and there is no need for dummy padding. Even, it is more clear what's going on, as you can see the address of each register, you don't have to rely on the compiler's padding behavior at all.
Use multiple adjacent anonymous bitfields. So instead of:
uint32_t :160;
for example, you'd have:
uint32_t :32;
uint32_t :32;
uint32_t :32;
uint32_t :32;
uint32_t :32;
One for each register you want to be anonymous.
If you have large spaces to fill it may be clearer and less error prone to use macros to repeat the single 32 bit space. For example, given:
#define REPEAT_2(a) a a
#define REPEAT_4(a) REPEAT_2(a) REPEAT_2(a)
#define REPEAT_8(a) REPEAT_4(a) REPEAT_4(a)
#define REPEAT_16(a) REPEAT_8(a) REPEAT_8(a)
#define REPEAT_32(a) REPEAT_16(a) REPEAT_16(a)
Then a 1344 (42 * 32 bit) space can be added thus:
struct
{
...
REPEAT_32(uint32_t :32;)
REPEAT_8(uint32_t :32;)
REPEAT_2(uint32_t :32;)
...
};
In the embedded systems arena, you can model hardware either by using a structure or by defining pointers to the register addresses.
Modeling by structure is not recommended because the compiler is allowed to add padding between members for alignment purposes (although many compilers for embedded systems have a pragma for packing the structure).
Example:
uint16_t * const UART1 = (uint16_t *)(0x40000);
const unsigned int UART_STATUS_OFFSET = 1U;
const unsigned int UART_TRANSMIT_REGISTER = 2U;
uint16_t * const UART1_STATUS_REGISTER = (UART1 + UART_STATUS_OFFSET);
uint16_t * const UART1_TRANSMIT_REGISTER = (UART1 + UART_TRANSMIT_REGISTER);
You could also use the array notation:
uint16_t status = UART1[UART_STATUS_OFFSET];
If you must use the structure, IMHO, the best method to skip addresses would be to define a member and not access it:
struct UART1
{
uint16_t status;
uint16_t reserved1; // Transmit register
uint16_t receive_register;
};
In one of our projects we have both constants and structs from different vendors (vendor 1 uses constants while vendor 2 uses structures).
geza's right that you really don't want to be using classes for this.
But, if you were to insist, the best way to add an unused member of n bytes' width, is simply to do so:
char unused[n];
If you add an implementation-specific pragma to prevent the addition of arbitrary padding to the class's members, this can work.
For GNU C/C++ (gcc, clang, and others that support the same extensions), one of the valid places to put the attribute is:
#include <stddef.h>
#include <stdint.h>
#include <assert.h> // for C11 static_assert, so this is valid C as well as C++
struct __attribute__((packed)) GPIO {
volatile uint32_t a;
char unused[3];
volatile uint32_t b;
};
static_assert(offsetof(struct GPIO, b) == 7, "wrong GPIO struct layout");
(example on the Godbolt compiler explorer showing offsetof(GPIO, b) = 7 bytes.)
To expand on #Clifford's and #Adam Kotwasinski's answers:
#define REP10(a) a a a a a a a a a a
#define REP1034(a) REP10(REP10(REP10(a))) REP10(a a a) a a a a
struct foo {
int before;
REP1034(unsigned int :32;)
int after;
};
int main(void){
struct foo bar;
return 0;
}
To expand on Clifford's answer, you can always macro out the anonymous bitfields.
So instead of
uint32_t :160;
use
#define EMPTY_32_1 \
uint32_t :32
#define EMPTY_32_2 \
uint32_t :32; \ // I guess this also can be replaced with uint64_t :64
uint32_t :32
#define EMPTY_32_3 \
uint32_t :32; \
uint32_t :32; \
uint32_t :32
#define EMPTY_UINT32(N) EMPTY_32_ ## N
And then use it like
struct A {
EMPTY_UINT32(3);
/* which resolves to EMPTY_32_3, which then resolves to real declarations */
}
Unfortunately, you'll need as many EMPTY_32_X variants as many bytes you have :(
Still, it allows you to have single declarations in your struct.
To define a large spacer as groups of 32 bits.
#define M_32(x) M_2(M_16(x))
#define M_16(x) M_2(M_8(x))
#define M_8(x) M_2(M_4(x))
#define M_4(x) M_2(M_2(x))
#define M_2(x) x x
#define SPACER int : 32;
struct {
M_32(SPACER) M_8(SPACER) M_4(SPACER)
};
I think it would be beneficial to introduce some more structure; which may, in turn, solve the issue of spacers.
Name the variants
While flat namespaces are nice, the issue is that you end up with a motley collection of fields and no simple way of passing all related fields together. Furthermore, by using anonymous structs in an anonymous union you cannot pass references to the structs themselves, or use them as template parameters.
As a first step, I would, therefore, consider breaking out the struct:
// GpioMap0.h
#pragma once
// #includes
namespace Gpio {
struct Map0 {
GPIO_MAP0_MODER;
GPIO_MAP0_OTYPER;
GPIO_MAP0_OSPEEDR;
GPIO_MAP0_PUPDR;
GPIO_MAP0_IDR;
GPIO_MAP0_ODR;
GPIO_MAP0_BSRR;
GPIO_MAP0_LCKR;
GPIO_MAP0_AFR;
GPIO_MAP0_BRR;
GPIO_MAP0_ASCR;
};
} // namespace Gpio
// GpioMap1.h
#pragma once
// #includes
namespace Gpio {
struct Map1 {
// fields
};
} // namespace Gpio
// ... others headers ...
And finally, the global header:
// Gpio.h
#pragma once
#include "GpioMap0.h"
#include "GpioMap1.h"
// ... other headers ...
namespace Gpio {
union Gpio {
Map0 map0;
Map1 map1;
// ... others ...
};
} // namespace Gpio
Now, I can write a void special_map0(Gpio:: Map0 volatile& map);, as well as get a quick overview of all available architectures at a glance.
Simple Spacers
With the definition split in multiple headers, the headers are individually much more manageable.
Therefore, my initial approach to exactly meet your requirements would be to stick with repeated std::uint32_t:32;. Yes, it adds a few 100s lines to the existing 8k lines, but since each header is individually smaller, it may not be as bad.
If you are willing to consider more exotic solutions, though...
Introducing $.
It is a little-known fact that $ is a viable character for C++ identifiers; it's even a viable starting character (unlike digits).
A $ appearing in the source code would likely raise eyebrows, and $$$$ is definitely going to attract attention during code reviews. This is something that you can easily take advantage of:
#define GPIO_RESERVED(Index_, N_) std::uint32_t $$$$##Index_[N_];
struct Map3 {
GPIO_RESERVED(0, 6);
GPIO_MAP2_BSRRL;
GPIO_MAP2_BSRRH;
GPIO_RESERVED(1, 5);
};
You can even put together a simple "lint" as a pre-commit hook or in your CI which looks for $$$$ in the committed C++ code and reject such commits.
Although I agree structs should not be used for MCU I/O port access, original question can be answered this way:
struct __attribute__((packed)) test {
char member1;
char member2;
volatile struct __attribute__((packed))
{
private:
volatile char spacer_bytes[7];
} spacer;
char member3;
char member4;
};
You may need to replace __attribute__((packed)) with #pragma pack or similar depending on your compiler syntax.
Mixing private and public members in a struct normally results in that memory layout is no longer guaranteed by C++ standard.
However if all non-static members of a struct are private, it is still considered POD / standard layout, and so are structs that embed them.
For some reason gcc produces a warning if a member of an anonymous struct is private so I had to give it a name. Alternatively, wrapping it into yet another anonymous struct also gets rid of the warning (this may be a bug).
Note that spacer member is not itself private, so data can still be accessed this way:
(char*)(void*)&testobj.spacer;
However such an expression looks like an obvious hack, and hopefully would not be used without a really good reason, let alone as a mistake.
Anti-solution.
DO NOT DO THIS: Mix private and public fields.
Maybe a macro with a counter to generate uniqie variable names will be useful?
#define CONCAT_IMPL( x, y ) x##y
#define MACRO_CONCAT( x, y ) CONCAT_IMPL( x, y )
#define RESERVED MACRO_CONCAT(Reserved_var, __COUNTER__)
struct {
GPIO_MAP1_CRL;
GPIO_MAP1_CRH;
GPIO_MAP1_IDR;
GPIO_MAP1_ODR;
GPIO_MAP1_BSRR;
GPIO_MAP1_BRR;
GPIO_MAP1_LCKR;
private:
char RESERVED[4];
public:
GPIO_MAP1_AFRL;
GPIO_MAP1_AFRH;
private:
char RESERVED[8];
};
The typical C-style approach:
#define LOG_ERRORS 1 // 2^0, bit 0
#define LOG_WARNINGS 2 // 2^1, bit 1
#define LOG_NOTICES 4 // 2^2, bit 2
#define LOG_INCOMING 8 // 2^3, bit 3
#define LOG_OUTGOING 16 // 2^4, bit 4
#define LOG_LOOPBACK 32 // and so on...
// Only 6 flags/bits used, so a char is fine
unsigned char flags;
// initialising the flags
flags = LOG_ERRORS;
//initialising to multiple values with OR (|)
flags = LOG_ERRORS | LOG_WARNINGS | LOG_INCOMING;
// sets to 1 + 2 + 8 i.e. bits 0, 1 and 3
// testing for a flag
// AND with the bitmask before testing with ==
if ((flags & LOG_WARNINGS) == LOG_WARNINGS)
...
// testing for multiple flags
// as above, OR the bitmasks
if ((flags & (LOG_INCOMING | LOG_OUTGOING))
== (LOG_INCOMING | LOG_OUTGOING))
...
Is there a better way in C++11, which keeps the old C style interface (LOG_INCOMING | LOG_OUTGOING)? i.e. How can I get rid of the "ugly" way to check which bits are set?
I have been looking at std::bitset but this latter only tests for positional queries (i.e. for example it can test if 3rd bit is set) and cannot test for something like this:
LOG_INCOMING | LOG_OUTGOING
I would replace your macros with static const ints (well, or an enum with explicit values), but other than that your implementation is just fine.
You should not replace good, solid, robust, clear, self-documenting, concise, reliable code with some new template monstrosity just because you can.
Your code is modern enough and this pattern is still very much in use.
I don't see anything wrong with the performance of the code that 0x/1y features will help. If it's already well tested, you probably want to avoid a re-write (especially if existing code depends on it).
If just want some ideas for how you could use features though, there are some different approaches you could take.
constexpr...
constexpr uint8_t bit(const uint8_t n) {
return 1 << n;
}
constexpr static const uint8_t LOG_ERRORS = bit(0);
constexpr static const uint8_t LOG_WARNINGS = bit(1);
if (flags & (LOG_ERROR | LOG_WARNINGS))
binary literals...
static const uint8_t LOG_ERRORS = 0b00000001;
static const uint8_t LOG_WARNINGS = 0b00000010;
if (flags & (LOG_ERRORS | LOG_WARNINGS))
variadic templates...
template<typename T, typename... Ts>
T bit_or(T t, Ts... ts) {
return t | bit_or(ts...);
}
template<typename T>
T bit_or(T t) {
return t;
}
template<typename T, typename... Ts>
bool any_set(T t, Ts... ts) {
return static_cast<bool>(t & (bit_or(ts...)));
}
constexpr uint8_t bit(const uint8_t n) {
return 1 << n;
}
constexpr static const uint8_t LOG_ERRORS = bit(0);
constexpr static const uint8_t LOG_WARNINGS = bit(1);
if (any_set(flags, LOG_ERRORS, LOG_WARNINGS))
My personal preference would be to avoid std::bitset, since it can't be directly evaluated in a boolean context. However, I might consider wrapping flags in a class, and using an enum class : uint8_t for the flags for type safety. The class would probably be something similar to Java's EnumSet. You could easily overload the bitwise operations (&, |, ^, ~, etc...) for it to preserve the C interface.
There is bitset, which, among other things, allows you to set an N bit to true; it also has some methods for conversions to unsigned and to string ( C++ string, not just a null terminated sequence of char C-style )
Other than that, I don't think that there is a more C++-ish way of doing this, but I'll probably keep an approach similar to what Lightness Races in Orbit just described, be conservative and don't add an overhead that you don't need .
What is the best practice for exporting a packed structure containing booleans?
I ask this because I'm trying to find the best way to do that. Current I do:
#ifndef __cplusplus
#if __STDC_VERSION__ >= 199901L
#include <stdbool.h> //size is 1.
#else
typedef enum {false, true} bool; //sizeof(int)
#endif
#endif
now in the above, the size of a boolean can be 1 or sizeof(int)..
So in a structure like:
#pragma pack(push, 1)
typedef struct
{
long unsigned int sock;
const char* address;
bool connected;
bool blockmode;
} Sock;
#pragma pack(pop)
the alignment is different if using C compared to C99 & C++. If I export it as an integer then languages where boolean is size 1 have alignment problems and need to pad the structure.
I was wondering if it would be best to typedef a bool as a char in the case of pre-C99 but it just doesn't feel right.
Any better ideas?
It depends on what you're looking for: preserve space but run a few extra instructions, or waste a few bytes but run faster.
If you're looking to be fast, but can "waste" a few bytes of space (i.e. a single value for each boolean flag, see sizeof bool discussion), your current approach is the superior. That is because it can load and compare the boolean values directly without having to mask them out of a packed field (see next).
If you're looking to preserve space then you should look into C bitfields:
struct Sock {
...
int connected:1; // For 2 flags, you could also use char here.
int blockmode:1;
}
or roll your own "flags" and set bits in integer values:
#define SOCKFLAGS_NONE 0
#define SOCKFLAGS_CONNECTED (1<<0)
#define SOCKFLAGS_BLOCKMODE (1<<1)
struct Sock {
...
int flags; // For 2 flags, you could also use char here.
}
Both examples lead to more or less the same code which masks bits and shifts values around (extra instructions) but is denser packed than simple bool values.
IMHO, using #pragma pack is more pain (in long term) than the gain (in short term).
It is compiler specific; non-standard and non-portable
I understand the embedded systems or protocols scenarios. With little extra effort, the code can be written pragma free.
I too want to pack my structure as much as possible and lay out the members in wider-first way as you did. However, I do not mind losing 2 bytes, if that allows my code to be standard-compliant and portable.
I would do the following three things:
Declare the flags as bool (you already did) and assign true/false
Put them as last members of the struct (you already did)
Use bitfield (as suggested by fellow stackers)
Combining these:
typedef struct Sock
{
long unsigned int sock;
const char* address;
bool connected : 1;
bool blockmode : 1;
} Sock;
In the pre-C99 case, it is risky to typedef char bool;. That will silently break code like:
bool x = (foo & 0x100);
which is supposed to set x to be true if that bit is set in foo. The enum has the same problem.
In my code I actually do typedef unsigned char bool; but then I am careful to write !! everywhere that an expression is converted to this bool. It's not ideal.
In my experience, using flags in an integral type leads to fewer issues than using bool in your structure, or bitfields, for C90.
Ok this might sound a little vague from the title, but that's because I have no idea how to word it differently. I'll try to explain what I mean: very often in certain libraries, the 'init' function accepts some parameters, but that parameter then accepts multiple parameters (right..). An example, would be like this:
apiHeader.h
#define API_FULLSCREEN 0x10003003
#define API_NO_DELAY 0x10003004
#define API_BLAH_BLAH 0x10003005
main.c:
apiInit(0, 10, 10, 2, API_FULLSCREEN | API_NO_DELAY | API_BLAH_BLAH);
How does this work? I can't find the answer anywhere, most likely because I don't know how it's actually called so I have no clue what to search for. It would be very useful in my current project.
Thanks in advance!
The parameter is usually called "$FOO flags" and the values are or-ed. The point is that the parameter is a numeric type that is constructed as the bitwise or of multiple possible values.
In the processing functions, the values are usually tested with a bitwise and:
if ( (flags & API_FULLSCREEN) != 0 )
You have to be careful to assign values in a way that keeps the OR operation linear. In other words, don't set the same bit in two different or-able values, like you did in your header. For example,
#define API_FULLSCREEN 0x1
#define API_NO_DELAY 0x2
#define API_BLAH_BLAH 0x4
works and allows you to deconstruct all combinations of flags in your function, but
#define API_FULLSCREEN 0x1
#define API_NO_DELAY 0x2
#define API_BLAH_BLAH 0x3
does not because API_FULLSCREEN | API_NO_DELAY == API_BLAH_BLAH.
Viewing from a higher level, a flags int is a poor man's variable argument list. If you consider C++, you should encapsulate such detail in a class or at least a std::bitset.
This fifth parameter is usually a mask. It works by defining several consts (probably an enum) with values that are powers of two, or combinations of them. Then they are encoded into a single value using |, and decoded using &. Example:
#define COLOUR_RED 0x01
#define COLOUR_GREEN 0x02
#define COLOUR_BLUE 0x04
#define COLOUR_CYAN (COLOUR_BLUE | COLOUR_GREEN) // 0x06
// Encoding
SetColour(COLOUR_RED | COLOUR_BLUE); // Parameter is 0x05
// Decoding
void SetColour(int colour)
{
if (colour & COLOUR_RED) // If the mask contains COLOUR_RED
// Do whatever
if (colour & COLOUR_BLUE) // If the mask contains COLOUR_BLUE
// Do whatever
// ..
}
What they are doing there is using binary OR to combine the flags together.
so what is actually happening is:
0x10003003 | 0x10003004 | 0x10003005 == 0x10003007
It's still one parameter, but the 3 flags will combine to create a unique value for that parameter which can be used in the function.
What you are defining as multiple parameter is strictly a single parameter from the function signature point of view.
As for handling multiple Options based on a single parameter, as you can see there is the bitwise Or Operator which sets a single value for the parameter value. The body of the function then uses individual bits to determine the complete settings.
Usually, one bit is allocated for one option and they usually have two state(true/false) values.
The parameter is usually called "flags" and contains an or-ed combination of a set of allowed values.
int flags = API_FULLSCREEN | API_NO_DELAY;
The function can the take this integer parameter and extract the individual items like this:
int fullscreen_set = flags & API_FULLSCREEN;
int no_delay_set = flags & API_NO_DELAY;
int blah_blah_set = flags & API_BLAH_BLAH;
For this to work one has to be carfull in how one chooses the numeric values for the API_* parameters.
Bitwise OR
Bitwise OR works almost exactly the same way as bitwise AND. The only difference is that only one of the two bits needs to be a 1 for that position's bit in the result to be 1. (If both bits are a 1, the result will also have a 1 in that position.) The symbol is a pipe: |. Again, this is similar to boolean logical operator, which is ||.
01001000 | 10111000 = 11111000
and consequently
72 | 184 = 248
So In you Method not a multiple parameter it is actully one parameter.
you can use Bitwise OR opearation on API_FULLSCREEN | API_NO_DELAY | API_BLAH_BLAH and passed it in method.
The example that you gave will not work as expected. What you do is to use a particular bit for a particular option - and the OR combines then
Example
#define OPT1 1
#define OPT2 2
#define OPT3 4
So bit 1 is for OPT1, bit 2 is for OPT2 etc.
So OPT1 | OPT3 sets bit 1 and 3 and gives a value of 5
In the function you can test if a particular option is required using the AND operator
So
void perform(int opts)
{
if (opts & OPT1)
{
// Do stuff for OPT1
}
...
The value of these parameters are defined in a way that they don't have any overlap. Something like this:
#define A 0x01
#define B 0x02
#define C 0x04
#define D 0x08
Given the above definitions, your can always determine which of the above variables have been ORed using the bitwise AND operator:
void foo(int param)
{
if(param & A)
{
// then you know that A has been included in the param
}
if(param & B)
{
// then you know that B has been included in the param
}
...
}
int main()
{
foo (A | C);
return 0;
}
It’s been awhile since I programmed in C/C++. For the life of me, I cannot remember (or find in Google) how to make the following work. I thought there was a shorthand way of writing a repeating string of bytes, like these:
0x00 => 0x00000000
0xFF => 0xFFFFFFFF
0xCD => 0xCDCDCDCD
For example, if I was to declare
int x = 0xCD;
printf("%d", x);
it would print 3452816845, not 205.
Am I going crazy?
Is it possible without doing runtime bit shifts (e.g., by making the preprocessor handle it)?
The simplest way is:
0x1010101u * x
I can't think of any syntax that could possibly be simpler or more self-explanatory...
Edit: I see you want it to work for arbitrary types. Since it only makes sense for unsigned types, I'm going to assume you're using an unsigned type. Then try
#define REPB(t, x) ((t)-1/255 * (x))
There's nothing like that by default in C. There's something similar in CSS (the color #123 is expanded to #112233), but that's completely different. :)
You could write a macro to do it for you, though, like:
#define REPEAT_BYTE(x) ((x) | ((x) << 8) | ((x) << 16) | ((x) << 24))
...
int x = REPEAT_BYTE(0xcd);
Unless you write your own macro, this is impossible. How would it know how long to repeat? 0xAB could mean 0xABABABABABABABABABABAB for all it knows (using the proposed idea).
There is no such shorthand. 0x00 is the same as 0. 0xFF is the same as 0x000000FF.
You could use some template trickery:
#include <iostream>
#include <climits>
using namespace std;
template<typename T, unsigned char Pattern, unsigned int N=sizeof(T)>
struct FillInt
{
static const T Value=((T)Pattern)<<((N-1)*CHAR_BIT) | FillInt<T, Pattern, N-1>::Value;
};
template<typename T, unsigned char Pattern>
struct FillInt<T, Pattern, 0>
{
static const T Value=0;
};
int main()
{
cout<<hex<<FillInt<unsigned int, 0xdc>::Value<<endl; // outputs dcdcdcdc on 32 bit machines
}
which adapts automatically to the integral type passed as first argument and is completely resolved at compile-time, but this is just for fun, I don't think I'd use such a thing in real code.
Nope. But you can use memset:
int x;
memset(&x, 0xCD, sizeof(x));
And you could make a macro of that:
#define INITVAR(var, value) memset(&(var), (int)(value), sizeof(var))
int x;
INITVAR(x, 0xCD);
You can use the preprocessor token concatenation:
#include <stdio.h>
#define multi4(a) (0x##a##a##a##a)
int main()
{
int a = multi4(cd);
printf("0x%x\n", a);
return 0;
}
Result:
0xcdcdcdcd
Of course, you have to create a new macro each time you want to create a "generator" with a different number of repetitions.