這不是特定於C++,而是關於2的補碼形式。在2的補碼中,最重要的比特不僅僅指示符號(該值爲負),而是2的冪(即,對於8比特的2的補數,最高有效比特將代表 - 2^7)。
要設置最負數,只應設置最重要的位。
// Disclaimer: this should work for *most* devices, but it
// is device-specific in that I am assuming 2's complement
// and I am also assuming that a char is 8-bits. In theory,
// you might find a custom chip where this isn't true,
// but any popular chip will probably have this behavior:
int number_of_digits_in_int = sizeof(int) * 8;
int most_significant_digit_index = number_of_digits_in_int - 1;
int most_negative_int = 1 << most_significant_digit_index;
爲了最大的正數,所有正位應設置:
// The complement of 0 has all bits set. This value, by the way
// is the same as "-1" in 2s complement form, but writing it
// this way for clarity as to its meaning.
int all_bits_set = ~(static_cast<int>(0));
// Using an XOR with the most negative integer clears the
// most-signficant sign bit, leaving only positive bits.
int largest_positive_int = all_bits_set^most_negative_int;
或者更簡單地說:
// Since the most negative integer has only the negative bit set,
// its complement has only the positive bits set.
int largest_positive_int = ~most_negative_int;
正如其他人所指出的,雖然,你應該只使用std::numeric_limits
。這也會讓你的代碼更加便攜,甚至在不使用二進制補碼的bizaare設備上工作,例如,更不用說你自己編寫的代碼越少,你犯的錯誤就越少。
出了什麼問題'limits'?你爲什麼重新實施它? – MadScientist
「有符號整數的二進制等價物是11111111111111111111111111111111」 - 這是什麼意思?你想說「簽名有32位」嗎? – anatolyg
是的,這是32位有符號整數@anatolyg – maruf