Programing

C의 크기가 "int"2 바이트 또는 4 바이트입니까?

lottogame 2020. 6. 18. 07:53
반응형

C의 크기가 "int"2 바이트 또는 4 바이트입니까?


C의 정수 변수가 2 바이트 또는 4 바이트를 차지합니까? 그것이 의존하는 요인은 무엇입니까?

대부분의 교과서에서는 정수 변수가 2 바이트를 차지한다고 말합니다. 그러나 정수 배열의 연속 주소를 인쇄하는 프로그램을 실행하면 4의 차이가 표시됩니다.


나는 그것과 같다는 것을 안다 sizeof(int). 의 크기 int는 실제로 컴파일러에 따라 다릅니다. 당시에는 프로세서가 16 비트 일 때 int2 바이트였습니다. 요즘에는 32 비트 및 64 비트 시스템에서 가장 자주 4 바이트입니다.

그럼에도 불구 sizeof(int)하고 프로그램이 실행되는 특정 시스템의 정수 크기를 얻는 가장 좋은 방법은 사용 입니다.

편집 :int 대부분의 64 비트 시스템에서 8 바이트의 잘못된 문장을 수정했습니다 . 예를 들어 64 비트 GCC에서 4 바이트입니다.


이것은 처음에 혼란 스러울 수있는 C의 요점 중 하나이지만 C 표준 은 지원되는 정수 유형 최소 범위 만 지정합니다 . int-32767 ~ 32767을 보유 할 수 있으며 16 비트가 필요합니다. 이 경우, int는 2 바이트입니다. 그러나 많은 현대 컴파일러가 int32 비트를 만듭니다 (이것은 또한 4 바이트를 매우 보편적으로 사용함).

책이 2 바이트라고 말하는 이유는 아마도 오래 되었기 때문일 것입니다. 한때는 이것이 표준이었습니다. 일반적으로 사용 sizeof중인 플랫폼에 몇 바이트가 있는지 알아 내려면 항상 연산자를 사용해야합니다 .

이를 해결하기 위해 C99는 특정 크기의 정수 (예 : int16_t또는)를 명시 적으로 요청할 수있는 새로운 유형을 추가했습니다 int32_t. 그 전에는 특정 너비의 정수를 얻는 보편적 인 방법이 없었습니다 (대부분의 플랫폼은 플랫폼별로 유사한 유형을 제공했지만).


구체적인 답변이 없습니다. 플랫폼에 따라 다릅니다. 구현 정의입니다. 2, 4 또는 다른 것일 수 있습니다.

아이디어 int는 주어진 플랫폼에서 16 비트 플랫폼의 16 비트, 32 비트 플랫폼의 32 비트, 64 비트 플랫폼의 64 비트와 같은 "단어"크기와 일치해야한다는 것입니다. 그러나 이전 버전과의 호환성을 위해 일부 컴파일러는 int64 비트 플랫폼에서도 32 비트를 고수하는 것을 선호 합니다.

int16 비트 워드 크기의 일부 임베디드 플랫폼을 사용하지 않으면 2 바이트의 시간 이 오래 걸렸습니다 (16 비트 플랫폼?). 당신의 교과서는 아마 아주 오래된 것입니다.


이 질문에 대한 답변은 사용중인 플랫폼에 따라 다릅니다.
그러나 플랫폼에 관계없이 다음 유형을 안정적으로 가정 할 수 있습니다.

 [8-bit] signed char: -127 to 127
 [8-bit] unsigned char: 0 to 255
 [16-bit]signed short: -32767 to 32767
 [16-bit]unsigned short: 0 to 65535
 [32-bit]signed long: -2147483647 to 2147483647
 [32-bit]unsigned long: 0 to 4294967295
 [64-bit]signed long long: -9223372036854775807 to 9223372036854775807
 [64-bit]unsigned long long: 0 to 18446744073709551615

C의 정수 변수가 2 바이트 또는 4 바이트를 차지합니까?

사용중인 플랫폼과 컴파일러 구성 방법에 따라 다릅니다. 신뢰할 수있는 유일한 대답은 sizeof연산자 를 사용 하여 특정 상황에서 정수의 크기를 확인하는 것입니다.


그것이 의존하는 요인은 무엇입니까?

size가 아니라 range 가 가장 잘 고려 될 수 있습니다 . 두 가지 모두 실제로 다를 수 있지만 우리가 볼 수 있듯이 크기보다 범위에 따라 변수 유형을 선택하는 것이 훨씬 더 멍청합니다. 또한 표준은 크기가 아닌 범위를 기준으로 정수 유형을 선택하는 것을 고려하도록 권장 하지만, 지금 은 표준 관행을 무시 하고 호기심 , 바이트 및 정수 표현을 살펴 보겠습니다. 토끼 구멍과 자신을 위해 그것을보고 ...sizeofCHAR_BIT


sizeof, 바이트 및 CHAR_BIT

C 표준 (위에 링크 됨)에서 가져온 다음 진술은 이것을 개선 할 수 없다고 생각하는 단어로 설명합니다.

sizeof연산자 식 또는 유형의 괄호 이름 일 수있다 피연산자의 크기 (바이트)를 산출한다. 크기는 피연산자의 유형에 따라 결정됩니다.

명확한 이해가 있다면 바이트 에 대한 논의로 이어질 것 입니다. 실제로 바이트에 몇 비트가 있는지 알려 주면 바이트 는 8 비트 라고 가정합니다 . 그것은 일반적인 2 바이트 (또는 4 바이트) 정수에 대해 이야기 할 때 고려되지 않는 미묘한 차이 중 하나 일뿐 입니다.CHAR_BIT

지금까지 내용을 마무리하겠습니다.

  • sizeof => 크기 (바이트)
  • CHAR_BIT => 바이트 단위의 비트 수

따라서, 시스템에 따라 sizeof (unsigned int)있을 수 있는 것보다 값이 큰 영 (단지 2 또는 4)의 경우로서 CHAR_BIT16 다음 단일 (여섯 비트) 바이트 열 여섯 비트 정수가 설명 표현에 충분한 비트가 표준 (아래 인용). 반드시 유용한 정보는 아닙니다. 그렇지 않습니까? 더 깊이 탐구합시다 ...


정수 표현

C 표준은 여기 에 모든 표준 정수 유형 (및 CHAR_BITfwiw)에 대한 최소 정밀도 / 범위를 지정합니다 . 이로부터 을 저장하는데 필요한 비트 수에 대한 최소값도출 할 수 있지만, 범위에 따라 변수를 선택할 수도 있습니다 . 그럼에도 불구하고이 답변에 필요한 세부 사항의 상당 부분이 여기에 있습니다. 예를 들어, 표준에 따르면 16 비트 이상의 스토리지가 필요합니다.unsigned int

UINT_MAX                                65535 // 2¹⁶ - 1

따라서 우리는 unsigned int2 바이트 를 얻는 곳 ( 최소한 ) 16 비트 필요 하다는 것을 알 수 있습니다 ( CHAR_BIT8이 가정 ) ... 그리고 그 한계가로 증가하면 2³² - 1사람들은 대신 4 바이트를 진술하고있었습니다. 이것은 당신이 관찰 한 현상을 설명합니다 :

대부분의 교과서에서는 정수 변수가 2 바이트를 차지한다고 말합니다. 그러나 정수 배열의 연속 주소를 인쇄하는 프로그램을 실행하면 4의 차이가 표시됩니다.

You're using an ancient textbook and compiler which is teaching you non-portable C; the author who wrote your textbook might not even be aware of CHAR_BIT. You should upgrade your textbook (and compiler), and strive to remember that I.T. is an ever-evolving field that you need to stay ahead of to compete... Enough about that, though; let's see what other non-portable secrets those underlying integer bytes store...

Value bits are what the common misconceptions appear to be counting. The above example uses an unsigned integer type which typically contains only value bits, so it's easy to miss the devil in the detail.

Sign bits... In the above example I quoted UINT_MAX as being the upper limit for unsigned int because it's a trivial example to extract the value 16 from the comment. For signed types, in order to distinguish between positive and negative values (that's the sign), we need to also include the sign bit.

INT_MIN                                -32768 // -(2¹⁵)
INT_MAX                                +32767 // 2¹⁵ - 1

Padding bits... While it's not common to encounter computers that have padding bits in integers, the C standard allows that to happen; some machines (i.e. this one) implement larger integer types by combining two smaller (signed) integer values together... and when you combine signed integers, you get a wasted sign bit. That wasted bit is considered padding in C. Other examples of padding bits might include parity bits and trap bits.


As you can see, the standard seems to encourage considering ranges like INT_MIN..INT_MAX and other minimum/maximum values from the standard when choosing integer types, and discourages relying upon sizes as there are other subtle factors likely to be forgotten such as CHAR_BIT and padding bits which might affect the value of sizeof (int) (i.e. the common misconceptions of two-byte and four-byte integers neglects these details).


C99 N1256 standard draft

http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf

The size of int and all other integer types are implementation defined, C99 only specifies:

  • minimum size guarantees
  • relative sizes between the types

5.2.4.2.1 "Sizes of integer types <limits.h>" gives the minimum sizes:

1 [...] Their implementation-defined values shall be equal or greater in magnitude (absolute value) to those shown [...]

  • UCHAR_MAX 255 // 2 8 − 1
  • USHRT_MAX 65535 // 2 16 − 1
  • UINT_MAX 65535 // 2 16 − 1
  • ULONG_MAX 4294967295 // 2 32 − 1
  • ULLONG_MAX 18446744073709551615 // 2 64 − 1

6.2.5 "Types" then says:

8 For any two integer types with the same signedness and different integer conversion rank (see 6.3.1.1), the range of values of the type with smaller integer conversion rank is a subrange of the values of the other type.

and 6.3.1.1 "Boolean, characters, and integers" determines the relative conversion ranks:

1 Every integer type has an integer conversion rank defined as follows:

  • The rank of long long int shall be greater than the rank of long int, which shall be greater than the rank of int, which shall be greater than the rank of short int, which shall be greater than the rank of signed char.
  • The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type, if any.
  • For all integer types T1, T2, and T3, if T1 has greater rank than T2 and T2 has greater rank than T3, then T1 has greater rank than T3

The only guarantees are that char must be at least 8 bits wide, short and int must be at least 16 bits wide, and long must be at least 32 bits wide, and that sizeof (char) <= sizeof (short) <= sizeof (int) <= sizeof (long) (same is true for the unsigned versions of those types).

int may be anywhere from 16 to 64 bits wide depending on the platform.


Mostly it depends on the platform you are using .It depends from compiler to compiler.Nowadays in most of compilers int is of 4 bytes. If you want to check what your compiler is using you can use sizeof(int).

main()
{
    printf("%d",sizeof(int));
    printf("%d",sizeof(short));
    printf("%d",sizeof(long));
}

The only thing c compiler promise is that size of short must be equal or less than int and size of long must be equal or more than int.So if size of int is 4 ,then size of short may be 2 or 4 but not larger than that.Same is true for long and int. It also says that size of short and long can not be same.


Is the size of C “int” 2 bytes or 4 bytes?

The answer is "yes" / "no" / "maybe" / "maybe not".

The C programming language specifies the following: the smallest addressable unit, known by char and also called "byte", is exactly CHAR_BIT bits wide, where CHAR_BIT is at least 8.

So, one byte in C is not necessarily an octet, i.e. 8 bits. In the past one of the first platforms to run C code (and Unix) had 4-byte int - but in total int had 36 bits, because CHAR_BIT was 9!

int is supposed to be the natural integer size for the platform that has range of at least -32767 ... 32767. You can get the size of int in the platform bytes with sizeof(int); when you multiply this value by CHAR_BIT you will know how wide it is in bits.


While 36-bit machines are mostly dead, there are still platforms with non-8-bit bytes. Just yesterday there was a question about a Texas Instruments MCU with 16-bit bytes, that has a C99, C11-compliant compiler.

On TMS320C28x it seems that char, short and int are all 16 bits wide, and hence one byte. long int is 2 bytes and long long int is 4 bytes. The beauty of C is that one can still write an efficient program for a platform like this, and even do it in a portable manner!


This depends on implementation, but usually on x86 and other popular architectures like ARM ints take 4 bytes. You can always check at compile time using sizeof(int) or whatever other type you want to check.

If you want to make sure you use a type of a specific size, use the types in <stdint.h>


#include <stdio.h>

int main(void) {
    printf("size of int: %d", (int)sizeof(int));
    return 0;
}

This returns 4, but it's probably machine dependant.


Is the size of C “int” 2 bytes or 4 bytes?

Does an Integer variable in C occupy 2 bytes or 4 bytes?

C allows "bytes" to be something other than 8 bits per "byte".

CHAR_BIT number of bits for smallest object that is not a bit-field (byte) C11dr §5.2.4.2.1 1

A value of something than 8 is increasingly uncommon. For maximum portability, use CHAR_BIT rather than 8. The size of an int in bits in C is sizeof(int) * CHAR_BIT.

#include <limits.h>
printf("(int) Bit size %zu\n", sizeof(int) * CHAR_BIT);

What are the factors that it depends on?

The int bit size is commonly 32 or 16 bits. C specified minimum ranges:

minimum value for an object of type int INT_MIN -32767
maximum value for an object of type int INT_MAX +32767
C11dr §5.2.4.2.1 1

The minimum range for int forces the bit size to be at least 16 - even if the processor was "8-bit". A size like 64 bits is seen in specialized processors. Other values like 18, 24, 36, etc. have occurred on historic platforms or are at least theoretically possible. Modern coding rarely worries about non-power-of-2 int bit sizes.

The computer's processor and architecture drive the int bit size selection.

Yet even with 64-bit processors, the compiler's int size may be 32-bit for compatibility reasons as large code bases depend on int being 32-bit (or 32/16).


This is a good source for answering this question.

But this question is a kind of a always truth answere "Yes. Both."

It depends on your architecture. If you're going to work on a 16-bit machine or less, it can't be 4 byte (=32 bit). If you're working on a 32-bit or better machine, its length is 32-bit.

To figure out, get you program ready to output something readable and use the "sizeof" function. That returns the size in bytes of your declared datatype. But be carfull using this with arrays.

If you're declaring int t[12]; it will return 12*4 byte. To get the length of this array, just use sizeof(t)/sizeof(t[0]). If you are going to build up a function, that should calculate the size of a send array, remember that if

typedef int array[12];
int function(array t){
    int size_of_t = sizeof(t)/sizeof(t[0]);
    return size_of_t;
}
void main(){
    array t = {1,1,1};  //remember: t= [1,1,1,0,...,0]
    int a = function(t);    //remember: sending t is just a pointer and equal to int* t
   print(a);   // output will be 1, since t will be interpreted as an int itselve. 
}

So this won't even return something different. If you define an array and try to get the length afterwards, use sizeof. If you send an array to a function, remember the send value is just a pointer on the first element. But in case one, you always knows, what size your array has. Case two can be figured out by defining two functions and miss some performance. Define function(array t) and define function2(array t, int size_of_t). Call "function(t)" measure the length by some copy-work and send the result to function2, where you can do whatever you want on variable array-sizes.

참고URL : https://stackoverflow.com/questions/11438794/is-the-size-of-c-int-2-bytes-or-4-bytes

반응형