programing

int의 최대값

bestcode 2022. 9. 1. 23:16
반응형

int의 최대값

C/C++에서 (컴파일러에 따라) 정수의 최대값을 구하는 코드가 있나요?Integer.MaxValueJava로 기능합니까?

C++의 경우:

#include <limits>

그 후

int imin = std::numeric_limits<int>::min(); // minimum value
int imax = std::numeric_limits<int>::max();

std::numeric_limits는 다른 유형으로 인스턴스화할 수 있는 템플릿 유형입니다.

float fmin = std::numeric_limits<float>::min(); // minimum positive value
float fmax = std::numeric_limits<float>::max();

C:

#include <limits.h>

그 후

int imin = INT_MIN; // minimum value
int imax = INT_MAX;

또는

#include <float.h>

float fmin = FLT_MIN;  // minimum positive value
double dmin = DBL_MIN; // minimum positive value

float fmax = FLT_MAX;
double dmax = DBL_MAX;

오래된 질문인 것은 알지만, 누군가가 이 솔루션을 사용할 수 있을 것입니다.

int size = 0; // Fill all bits with zero (0)
size = ~size; // Negate all bits, thus all bits are set to one (1)

지금까지 우리는 -1을 가지고 있다. 'till size is signed int.

size = (unsigned int)size >> 1; // Shift the bits of size one position to the right.

표준에서 말하는 바와 같이, 에서 시프트되는 비트는 변수가 서명되어 있고 음수인 경우 1이고 변수가 부호 없는 경우 또는 부호 있는 경우 0입니다.

사이즈가 부호화되어 음수이기 때문에 부호 비트가 1인 경우는 별로 도움이 되지 않기 때문에 부호 없는 int로 캐스트하고 대신 0으로 전환하도록 강제하고 부호 비트를 0으로 설정하고 다른 모든 비트는 1로 유지합니다.

cout << size << endl; // Prints out size which is now set to maximum positive value.

마스크 및 xor를 사용할 수도 있지만 변수의 정확한 비트 크기를 알아야 합니다.비트 프런트 전환으로 머신 또는 컴파일러에 int의 비트 수를 알 필요도 없고 추가 라이브러리를 포함할 필요도 없습니다.

#include <climits>
#include <iostream>
using namespace std;

int main() {
  cout << INT_MAX << endl;
}
#include <iostrema>

int main(){
    int32_t maxSigned = -1U >> 1;
    cout << maxSigned << '\n';
    return 0;
}

아키텍처에 의존할 수도 있지만 적어도 제 설정에서는 동작합니다.

이것은 부호 있는 정수의 최대값을 취득하기 위해 사용하는 매크로입니다.이것은 사용되는 부호 있는 정수 타입의 사이즈와는 무관하며, gcc - Woverflow에 대해서는 불평하지 않습니다.

#define SIGNED_MAX(x) (~(-1 << (sizeof(x) * 8 - 1)))

int a = SIGNED_MAX(a);
long b = SIGNED_MAX(b);
char c = SIGNED_MAX(c); /* if char is signed for this target */
short d = SIGNED_MAX(d);
long long e = SIGNED_MAX(e);

좋아요. 저는 (필리페 드 마이어의) 이전 답변에 대해 코멘트할 필요도, 스코어를 올릴 필요도 없습니다.따라서 그의 정의를 사용한 새로운 예가 서명되었습니다.서명되지 않은 유형에 대해 MAX가 3차적으로 확장되었습니다.

// We can use it to define limits based on actual compiler built-in types also: 
#define INT_MAX   SIGNED_MAX(int)
// based on the above, we can extend it for unsigned types also:
#define UNSIGNED_MAX(x) (  (SIGNED_MAX(x)<<1) | 1 ) // We reuse SIGNED_MAX
#define UINT_MAX  UNSIGNED_MAX(unsigned int) // on ARM: 4294967295
// then we can have:
unsigned int width = UINT_MAX;

이 헤더 또는 저 헤더를 사용하는 것과 달리 여기서는 컴파일러의 실제 유형을 사용합니다.

다음과 같은 코드를 작성해 보는 것은 어떨까요?

int  max_neg = ~(1 << 31);
int  all_ones = -1;
int max_pos = all_ones & max_neg;

어때(1 << (8*sizeof(int)-2)) - 1 + (1 << (8*sizeof(int)-2))이것은 같은 것입니다.2^(8*sizeof(int)-2) - 1 + 2^(8*sizeof(int)-2).

한다면sizeof(int) = 4 => 2^(8*4-2) - 1 + 2^(8*4-2) = 2^30 - 1 + 20^30 = (2^32)/2 - 1 [max signed int of 4 bytes].

사용할 수 없습니다.2*(1 << (8*sizeof(int)-2)) - 1넘칠 것 같으니까(1 << (8*sizeof(int)-2)) - 1 + (1 << (8*sizeof(int)-2))작동하다.

언급URL : https://stackoverflow.com/questions/1855459/maximum-value-of-int

반응형