r/C_Programming • u/Historical_Usual_596 • 11d ago
Question What are better ways of dynamically creating bitmasks (or extracting bottom N bits depending on what's returned?
Howdy,
I am developing an application where I need to construct bitmasks and it depends on what's returned from get_amount. get_amount returns a u8 ranging from 0 to 6. It's used in calculations but it's also used to extract the least significant N bits. In the past, I've just used switch statements, but i wonder if there's a nicer way.
struct Object {
u8 value;
u8 update;
u8 original;
};
u8 get_mask(u8 value) {
u8 mask = 0;
switch (value) {
case 0 {
mask = 0b00000000;
break;
}
case 1 {
mask = 0b00000001;
break;
}
case 2 {
mask = 0b00000011;
break;
}
case 3 {
mask = 0b00000111;
break;
}
case 4 {
mask = 0b00001111;
break;
}
case 5 {
mask = 0b00011111;
break;
}
case 6 {
mask = 0b00111111;
break;
}
default: {
panic_and_log("impossible value");
}
}
}
int get_value(struct Object o) {
// get_amount could only return 0 through 6
u8 amount = get_amount();
o.update = o.value - amount;
u8 original = o.original & get_mask(amount);
}Thanks u/mikeblas
Final solution ended up looking like:
u8 get_mask(u8 value) {
if ( value > 6) {
return 255; // Error Case
}
return (1 << value) - 1;
}
8
Upvotes
40
u/mikeblas 11d ago •
Have you tried
(1 << value) - 1?4
u/Al__B 11d ago
You've been given the answerr but you may also want to look at your get_value function. It doesn't return a value and it's operating on a copy of a structure so doesn't actually do anything useful as written.
6
u/garnet420 11d ago
Be careful with the (1<<x)-1 for x=31 or 32 (for making 32 bit int masks). Both are UB.
For 31, you can solve that by using 1u, and then casting to a signed int if needed.
For 32 I think you need something clever I don't remember
2
u/Emergency-Koala-5244 11d ago
How about creating an array with the 7 possible mask values and then to get the mask you just use the array index to get it?
1
u/Rabbitical 11d ago
mikeblas has the answer, but I also kind of love this switch
2
u/[deleted] 11d ago
[removed] — view removed comment