[英]Obtaining max of unsigned integer with bitwise not on zero value
我試圖獲取某個無符號整數類型的最大值,而不包括像<limits>
這樣的任何頭。 所以我想我只是翻轉無符號整數值0的位。
#include <iostream>
#include <limits>
int main()
{
std::cout << (~0U) << '\n'; // #1
std::cout << (std::numeric_limits< unsigned >::max()) << '\n'; // #2
return 0;
}
我對這些之間的微妙差異並不是很有經驗。 這就是為什么我要問使用第一種方法是否會發生某些意外行為或某些平台/架構問題。
...獲取某個無符號整數類型的最大值而不包括任何頭
只需指定值-1
unsigned_type_of_choice max = -1;
將-1
(即int
)轉換為任何無符號類型會導致number的值比最大值減1 更大 。
以下內容未提供目標類型的最大值。 當目標類型范圍超出unsigned
范圍時,它會失敗,這是~0U
的類型。 @Christopher Oicles
// problem
unsigned_type_of_choice max_wannabe = ~0U;
您不應該將~0U
分配給任何無符號類型, chux的答案已經解釋了原因。
對於C ++,使用以下內容可以獲得所有無符號類型的最大可能值。
template <typename T>
T max_for_unsigned_type() {
return ~(static_cast<T> (0));
}
你正在否定你的確切類型的零 。 我使用詳細的函數名稱,因為它不應該用於簽名值。 問題是,對於檢查簽名,最簡單的方法是包括一個額外的頭,即type_traits 。 那么這個其他答案將是有用的。
用法:
max_for_unsigned_type<uint8_t> ();
max_for_unsigned_type<uint16_t> ();
max_for_unsigned_type<uint32_t> ();
max_for_unsigned_type<uint64_t> ();
max_for_unsigned_type<unsigned> ();
返回值:(請參閱此處的測試代碼)
255
65535
4294967295
18446744073709551615
4294967295
注意:對簽名類型執行此操作要困難得多,請參閱以編程方式確定有符號整數類型的最大值 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.