3 ms·
unsigned int swapbits(unsigned int a) { bool bit6 = a & (1 << 5); bool bit17 = a & (1 << 16); if (bit6 == bit17) return a; //bits are th
by deanmen 5y ago
unsigned int swapbits(unsigned int a)
{
bool bit6 = a & (1 << 5);
bool bit17 = a & (1 << 16);
if (bit6 == bit17) return a; //bits are the same, do nothing
return (a ^ (1 << 5) ^ (1 << 16)); // flip both 6th and 17th bits
}
- errcorrectcode 5y agoGross and not portable C99. #define B6 (1<<5) #define B17 (1<<16) unsigned swapbits(unsigned a) { return ((a & B6 == a & B17) ? a : (a ^ (B6 | B17))); } Here's some BFP: unsigned swapbits(unsigned a) { unsigned flip = (a & B6 == a & B17); return (a ^ ((flip<<5) | (flip<<16))); } int and double are C's implicit lingua francas for underspecified literals and implicit type conversions. Throwing int everywhere is redundant like "ATM machine."
- deanmen 5y agoThe definition of flip requires parenthesis (a & B6) == (a & B17) as == has higher precedence than and. int is required in C++ but not in C as you said.