Flags & Hex Numbering

Hi :)
I am reading a tutorial where the guy labels some flags in hex
Flag1=0x000001;
Flag2=0x000002;
Flag3=0x000003;
He then says
" Now, notice how we have them numbered in hex. This is because we're treating the Flags in binary. This way, we can activate multiple flags at once"
I don't understand this, because surely the binary is the same even
if you use 1,2,3,4.... I just can't figure out what the advantage is
he is talking about. Can anyone shed some light? Cheers!
Hex is good when working with flags/binary because they line up so that one hexadecimal digit is 4 bits. It is easy to see that 0x23 is 0010 0011 in binary. It is not as easy if written as decimal 35. For small numbers < 8 it doesn't matter if you use hexadecimals but you might want to use it anyway for consistency.

Note that in your example flag3 has both bit 1 and bit 2 set. If the intention is to have bit 3 set you should use 0x000004.
Last edited on
Suppose you want to schedule things for certain days of the week. You could use a set of flags like this:

1
2
3
4
5
6
7
char SUN = 0x01;
char MON = 0x02;
char TUES = 0x04;
char WED = 0x08;
char THURS = 0x10;
char FRI = 0x20;
char SAT = 0x40; 


When you want to refer to all weekdays, you can define:

char WEEKDAYS = MON | TUES | WED | THURS | FRI;

If you want to schedule something on Tuesdays and Thursdays, you can do

event.schedule(TUES | THURS);

This could be done with decimal values, but it is harder to understand when reading the code:

1
2
3
4
5
6
7
char SUN = 1;
char MON = 2;
char TUES = 4;
char WED = 8;
char THURS = 16;
char FRI = 32;
char SAT = 64; 
Thanks guys! Exactly what I needed
Topic archived. No new replies allowed.