gpt4 book ai didi

c++ - operator>> 和 << 输出在输出时为空

转载 作者:太空宇宙 更新时间:2023-11-04 16:31:44 24 4
gpt4 key购买 nike

我不明白为什么当我输出这两个函数时它们的输出都为空:

class uint128_t{

private:
uint64_t UPPER, LOWER;

public:
// constructors
uint128_t(){
UPPER = 0;
LOWER = 0;
}

template <typename T>
uint128_t(T rhs){
UPPER = 0;
LOWER = (uint64_t) rhs;
}

template <typename S, typename T>
uint128_t(const S upper_rhs, const T lower_rhs){
UPPER = (uint64_t) upper_rhs;
LOWER = (uint64_t) lower_rhs;
}

uint128_t(const uint128_t & rhs){
UPPER = rhs.UPPER;
LOWER = rhs.LOWER;
}

// RHS input args only

// assignment operator
template <typename T> uint128_t & operator=(T rhs){
UPPER = 0;
LOWER = (uint64_t) rhs;
return *this;
}

uint128_t & operator=(uint128_t & rhs){
UPPER = rhs.UPPER;
LOWER = rhs.LOWER;
return *this;
}


uint128_t operator<<(int shift){
if (shift >= 128)
return uint128_t(0, 0);
else if (shift == 64)
return uint128_t(LOWER, 0);
else if (shift < 64)
return uint128_t((UPPER << shift) + (LOWER >> (64 - shift)), LOWER << shift);
else if ((128 > shift) && (shift > 64)){
uint128_t a =uint128_t(LOWER << (shift - 64), 0);
// a will show the correct values
std::cout << a.upper() << " " << a.lower() << std::endl;
return uint128_t(LOWER << (shift - 64), 0);
// in the program that includes this, printing out the values show 0 0
}
}

uint128_t operator>>(int shift){
if (shift >= 128)
return uint128_t(0, 0);
else if (shift == 64)
return uint128_t(0, UPPER);
else if (shift <= 64)
return uint128_t(UPPER >> shift , ((UPPER << (64 - shift))) + (LOWER >> shift));
else if ((128 > shift) && (shift > 64))
return uint128_t(0, (UPPER >> (shift - 64)));
}

uint128_t operator<<=(int shift){
*this = *this << shift;
return *this;
}

uint128_t operator>>=(int shift){
*this = *this >> shift;
return *this;
}

const uint64_t upper() const {
return UPPER;
}

const uint64_t lower() const {
return LOWER;
}

// lots of other stuff

};

int main(){

uint128_t a(0x123456789abcdef1ULL, 0x123456789abcdef1ULL);

a>>= 127; // or a <<= 127;
std::cout <<a.upper() << " " <<a.lower() << std::endl;
return 0;
}

http://ideone.com/jnZI9

谁能知道为什么?

最佳答案

您的 int 是 128 位,您正在将它向下(右)移动 127 位,这意味着最高位将移至最低位,所有其他位将为 0。

但是你的例子中的 int 是 0x1....0x1(最高半字节)在二进制中是 0001,这确实没有设置高位。所以 0 是正确的输出。

如果您将 0x1... 更改为 0x8...(或任何高于 0x7 的值),您很可能会在输出。

关于c++ - operator>> 和 << 输出在输出时为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6156862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com