4 ms·
I’ve been programming C++ on a daily basis for more than 20 years and literally never use the >> operator. Never. Not rarely, never.
by AaronAPU 1y ago
I’ve been programming C++ on a daily basis for more than 20 years and literally never use the >> operator. Never. Not rarely, never.
- pklausler 1y agoHow do you shift bits to the right?
- pdpi 1y agoManipulating bit patterns isn't really that common in most workloads.
- voxelghost 1y agoright_shifted = value / (1 << bits)
- deleted 1y ago[deleted]
- taneq 1y agoDivision is slow, though. You should use something like: right_shifted = (int)(value * pow(2, -bits) - 0.5)
- jandrewrogers 1y agoOr just rely on the compiler to automatically do trivial conversions. Which are pretty reliable these days.
- account42 1y agoI'm pretty sure the post you are responding to is not seriously suggesting using floating point multiplication and exponentiation as a performance optimization ;)
- voxelghost 1y agoOffcourse not, that would be silly. Just overload the ^ operator like any normal person. #include <iostream> #include <bitset> class Bits { unsigned value; public: explicit Bits(unsigned v) : value(v) {} // Shift operator ^ : positive = left, negative = right Bits operator^(int shift) const { if (shift > 0) { return Bits(value << shift); } else if (shift < 0) { return Bits(value >> -shift); } else { return *this; // no shift } } friend std::ostream& operator<<(std::ostream& os, const Bits& b) { return os << std::bitset<8>(b.value); // print 8 bits } }; int main() { Bits x(0b00001111); std::cout << "x = " << x << "\n"; std::cout << "x ^ 2 = " << (x ^ 2) << " (shift left 2)\n"; std::cout << "x ^ -2 = " << (x ^ -2) << " (shift right 2)\n"; }
- voxelghost 1y agoI dont trust my intel FPU to accurately representa that ;-)
- loeg 1y agoI didn't mention >>.
- CyberDildonics 1y agoWhat about sometimes?