Question about shifting, portability

A

Andy

Hey all,

Is it a good/bad practice to shift right then back left to clear (set to
zero) the 'n' LSBs of an integer?

e.g. if n=2

unsigned int num = 13; // 1101
num = (num >> 2); // 11
num = (num << 2); // 1100



Thanks
 
V

Victor Bazarov

Andy said:
Is it a good/bad practice to shift right then back left to clear (set to
zero) the 'n' LSBs of an integer?

Is it better than a bitwise 'AND'? I'd use the bitwise 'AND'...
e.g. if n=2

unsigned int num = 13; // 1101
num = (num >> 2); // 11
num = (num << 2); // 1100

I'd probably do

template<int bits> inline unsigned lowbits() {
return (1 << bits) - 1;
}

template<int bits, class T> inline void clearlowbits(T &t) {
t &= ~ lowbits<bits>();
}

...
unsigned num = 13;
clearlowbits<2>(num);


V
 
M

msalters

Victor Bazarov schreef:
Is it better than a bitwise 'AND'? I'd use the bitwise 'AND'...


I'd probably do

template<int bits> inline unsigned lowbits() {
return (1 << bits) - 1;
}

That's not (yet) an ICE; defining it as

template< int bits> struct lowbits {
enum { mask = (1 << bits) - 1 };
};

gives you the constant lowbits<2>::mask . This mask can be used
everywhere the function result can be used, plus it can be used
in array definitions etc.

HTH,
Michiel Salters
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top