program story

uint 대 int 사용

inputbox 2020. 10. 14. 07:47
반응형

uint 대 int 사용


나는 C # 프로그래머가 어디에서나 int를 사용하는 경향이 있고 거의 uint에 의존하지 않는 경향이 있음을 잠시 관찰했습니다. 그러나 나는 그 이유에 대해 만족스러운 답을 찾지 못했습니다.

상호 운용성이 목표 인 경우 모든 CLI 언어가 부호없는 정수를 지원하는 것은 아니므로 uint가 공용 API에 나타나지 않아야합니다. 그러나 그것은 내부 클래스에서도 int가 왜 그렇게 널리 퍼져 있는지 설명하지 못합니다. 이것이 BCL에서 uint가 드물게 사용되는 이유라고 생각합니다.

C ++에서 음수 값이 의미가없는 정수가 있으면 부호없는 정수를 선택합니다.

이는 음수가 허용되지 않거나 예상되지 않음을 명확하게 나타내며 컴파일러가 일부 검사를 수행합니다. 또한 배열 인덱스의 경우 JIT가 하한 검사를 쉽게 삭제할 수 있다고 생각합니다.

그러나 int 및 unit 유형을 혼합 할 때 추가주의와 캐스트가 필요합니다.

uint를 더 사용해야합니까? 왜?


uintBCL에서 사용되지 않는 이유에 대한 귀하의 관찰이 주된 이유라고 생각합니다.

UInt32는 CLS 규격이 아니므로 공용 API에서 사용하기에 완전히 부적절합니다. 비공개 API에서 uint를 사용하려는 경우 다른 유형으로 변환하는 것을 의미합니다. 일반적으로 유형을 동일하게 유지하는 것이 더 쉽고 안전합니다.

나는 또한 이것이 주로 BCL에서 일반적이지 않기 때문에 C #이 사용되는 유일한 언어 인 경우에도 C # 개발에서 일반적이지 않다고 생각합니다. 일반적으로 개발자는 빌드중인 프레임 워크의 스타일을 (고맙게도) 모방하려고합니다. C #의 경우 이는 API를 공용 및 내부로 가능한 한 .NET Framework BCL과 비슷하게 보이게 만드는 것을 의미합니다. 이것은 uint를 아껴 사용함을 의미합니다.


int는보다 입력하기가 더 짧습니다 uint.


일반적으로 int충분합니다. 다음 조건을 모두 충족 할 수있는 경우 다음을 사용할 수 있습니다 uint.

  • 공용 API uint용이 아닙니다 (CLS 규격이 아니기 때문에 ).
  • 음수가 필요하지 않습니다.
  • 추가 범위가 필요할 수도 있습니다.
  • 당신은되어 있지 과의 비교에서 사용 < 0이 결코 없기 때문에, true.
  • 당신은되어 있지 과의 비교에서 사용 >= 0이 결코 없기 때문에, false.

마지막 요구 사항은 종종 잊혀지고 버그가 발생합니다.

static void Main(string[] args)
{
    if (args.Length == 0) return;
    uint last = (uint)(args.Length - 1);

    // This will eventually throw an IndexOutOfRangeException:
    for (uint i = last; i >= 0; i--)
    {
        Console.WriteLine(args[i]);
    }
}

1) 나쁜 습관. 진지하게. C / C ++에서도.

일반적인 for패턴을 생각해보십시오 .

for( int i=0; i<3; i++ )
    foo(i);

거기에 정수를 사용할 이유가 전혀 없습니다. 음수 값은 없습니다. 그러나 거의 모든 사람이 (적어도) 두 개의 다른 "스타일"오류가 포함되어 있더라도 간단한 루프를 수행합니다.

2) int기계의 기본 유형으로 인식됩니다.


I 선호 uintint음의 수가 허용 가능한 값의 범위 내에 실제로 아니라면. 특히, int매개 변수를 받아들이지 ArgumentException숫자가 0보다 작 으면 an을 던지는 것은 어리석은 일입니다 uint.!

나는 그것이 잘 사용되지 않는다는 데 동의하며 uint다른 모든 사람들이 더 많이 사용하도록 권장합니다.


나는 int가 거의 100을 넘지 않는 낮은 수준의 응용 프로그램 계층에서 프로그래밍하므로 음수 값은 문제가되지 않습니다. 그러나 어떤 경우에는 장치의 이벤트 플래그를 처리하는 하드웨어에 인터페이스 할 때 플래그가 가장 왼쪽 (가장 높은) 비트를 사용할 수있는 경우에 단위가 중요합니다.

솔직히, 내 작업의 99.9 %에 대해 ushort를 쉽게 사용할 수 있었지만 int는 ushort보다 훨씬 좋은 소리를냅니다.


C #에서 Direct3D 10 래퍼를 만들었으며 매우 큰 정점 버퍼를 만들려면 uint를 사용해야합니다. 비디오 카드의 큰 버퍼는 부호있는 정수로 표시 할 수 없습니다.

UINT는 매우 유용하며 달리 말하는 것은 어리 석습니다. 누군가가 uint를 사용할 필요가 없다고 생각하는 사람은 아무도 없을 것입니다.


그냥 게으름이라고 생각합니다. C #은 본질적으로 리소스가 상대적으로 많은 데스크톱 및 기타 컴퓨터에서 개발하기위한 선택입니다.

C and C++, however, has deep roots in old systems and embedded systems where memory is sparse, so programmers are used to think carefully what datatype to use. C# programmers are lazy, and since there are enough resources in general, nobody really optimizes memory usage (in general, not always of course). Event if a byte would be sufficient, a lot of C# programmers, including me, just use int for simplicity. Moreover, a lot of API functions accept ints, so it prevents casting.

I agree that choosing the correct datatype is good practice, but I think the main motivation is laziness.

Finally, choosing an integer is more mathematically correct. Unsigned ints don't exist in math (only natural numbers). And since most programmers have a mathematical background, using an integer is more natural.


I think a big part of the reason is that when C first came out most of the examples used int for brevity's sake. We rejoiced at not having to write integer like we did with Fortran and Pascal, and in those days we routinely used them for mundane things like array indices and loop counters. Unsigned integers were special cases for large numbers that needed that last extra bit. I think it's a natural progression that C habits continued into C# and other new languages like Python.


Some languages (e.g. many versions of Pascal) regard unsigned types as representing numeric quantities; an operation between an unsigned type and a signed type of the same size will generally be performed as though the operands were promoted to the next larger type (in some such languages, the largest type has no unsigned equivalent, so such promotion will always be possible).

Other languages (e.g. C) regard N-bit unsigned types as a group which wraps around modulo 2^N. Note that subtracting N from a member of such a group doesn't represent numerical subtraction, but rather yields the group member which, when N is added to it, would yield the original. Arguably, certain operations involving mixtures of signed and unsigned values don't really make sense and should perhaps have been forbidden, but even code which is sloppy with its specifications of things like numeric literals will usually work, and code has been written which mixes signed and unsigned types and, despite being sloppy, does work, that the spec isn't apt to change any time soon.

It's a lot easier to work exclusively with signed types than to work out all the intricacies of interactions between signed and unsigned types. Unsigned types are useful when decomposing large numbers out of smaller pieces (e.g. for serialization) or for reconstituting such numbers, but in general it's better to simply use signed numbers for things that actually represent quantities


I know this is probably an old thread but I wanted to give some clarification.

Lets take an int8 you can store –128 to 127 and it uses 1 byte that is a total of 127 positive numbers.
When you use an int8 one of the bits is used for the negative numbers -128.
When you use a Uint8 you give the negative numbers to the positive so this allows you to use 255 positive numbers with the same amount of storage 1 byte.
The only draw back is the you have now lost the capability to use negative values.
Another problem with this is not all programming languages and databases support this.
The only reason you would use this in my opinion is when you need to be efficient in like gaming programming and you have to store large non negative numbers. This is why not many programs use this it.

The main reason is storage is not a problem and you can't use it flexibly with other software, plugins, Database, or Api's. Also for example a bank would need negative numbers to store money etc.

I hope this will help someone.

참고URL : https://stackoverflow.com/questions/3095805/using-uint-vs-int

반응형