Remix.run Logo
voxelghost 5 days ago

right_shifted = value / (1 << bits)

taneq 5 days ago | parent | next [-]

Division is slow, though. You should use something like:

right_shifted = (int)(value * pow(2, -bits) - 0.5)

jandrewrogers 5 days ago | parent | next [-]

Or just rely on the compiler to automatically do trivial conversions. Which are pretty reliable these days.

account42 5 days ago | parent [-]

I'm pretty sure the post you are responding to is not seriously suggesting using floating point multiplication and exponentiation as a performance optimization ;)

voxelghost 4 days ago | parent [-]

Offcourse 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 5 days ago | parent | prev [-]

I dont trust my intel FPU to accurately representa that ;-)

5 days ago | parent | prev [-]
[deleted]