블로그 이미지
Every unexpected event is a path to learning for you.

카테고리

분류 전체보기 (2738)
Unity3D (817)
Programming (475)
Python (8)
TinyXML (5)
STL (13)
D3D (3)
MFC (1)
C/C++ (54)
C++/CLI (45)
C# (250)
WinForm (6)
WPF (5)
Math (10)
A.I. (1)
Win32API (11)
Algorithm (3)
Design Pattern (7)
UML (1)
MaxScript (1)
FMOD (4)
FX Studio (1)
Lua (2)
Terrain (1)
Shader (3)
boost (2)
Xml (2)
JSON (4)
Etc (11)
Monad (1)
Html5 (4)
Qt (1)
Houdini (0)
Regex (11)
Server (33)
Unreal (4)
Gamebryo (56)
Tip & Tech (228)
협업 (58)
3DS Max (3)
Game (12)
Utility (136)
Etc (96)
Link (32)
Portfolio (19)
Subject (90)
iOS,OSX (53)
Android (14)
Linux (5)
잉여 프로젝트 (2)
게임이야기 (3)
Memories (20)
Interest (38)
Thinking (38)
한글 (30)
PaperCraft (5)
Animation (408)
Wallpaper (2)
재테크 (18)
Exercise (3)
나만의 맛집 (3)
냥이 (10)
육아 (16)
Total
Today
Yesterday
04-30 00:00
32비트 정수형인 int 는 "unsigned int"라 하더라도

4294967295 (사십이억 구천사백구십육만 칠천이백구십오)

밖에는 표현하지 못하기에, 64비트 정수가 필요합니다.

비주얼C++ 에서는 버전 4.0부터 __int64 라는 이름으로 지원되고 있습니다.


__int64, unsigned __int64 선언, printf() 출력 예제


#include <stdio.h>


void main(void) {

  // signed long long
  // -9223372036854775808 ~ 9223372036854775807
           __int64  x = 9223372036854775807i64;

  // unsigned long long
  // 0 ~ 18446744073709551615
  unsigned __int64 ux = 0xFFFFFFFFFFFFFFFFui64;




  // signed
  printf("%I64d\n", x); // 출력 결과: 9223372036854775807

  // unsigned
  printf("%I64u\n", ux); // 출력 결과: 18446744073709551615

}


출처 :  http://mwultong.blogspot.com/2006/10/c-64-int64-printf.html
반응형
Posted by blueasa
, |
반응형
Posted by blueasa
, |
This EE article provides examples of conversion techniques for various types of string variables:  classic C-style strings, MFC/ATL CStrings, and STL's std::string data type.

Convert Integer to String


int to C-style (NULL-terminated char[]) string

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
int   n=1234567890;
char  szResult[12];

#include <stdio.h>
...
sprintf
(   szResult, "%d", n );               // use "%u" for unsigned int
sprintf_s
( szResult, sizeof(szResult), "%d", n );  // "safe" version

//------------------------------------- alternative: itoa
#include <stdlib.h>
...
_itoa
(   n, szResult, 10 );
_itoa_s
( n, szResult, sizeof(szResult), 10);    // "safe" version


int to ATL/MFC CString

1:
2:
3:
4:
5:
6:
#include <cstringt.h>
...
int     n;
CString sResult;

sResult
.Format( "%d", n );    // use "%u" for unsigned int


int to STL std::string

1:
2:
3:
4:
5:
6:
7:
8:
9:
#include <iostream>
#include <sstream>
...
int         n;
std
::string sResult;

std
::ostringstream ostr;
ostr
<< n;
sResult
= ostr.str();



Convert String to Integer


C-style (NULL-terminated char[]) string to int

1:
2:
3:
4:
5:
6:
#include <stdlib.h>
...
char szNumber[12]= "1234567890";
int  nResult;

nResult
= atoi( szNumber );


ATL/MFC CString to int

1:
2:
3:
4:
5:
6:
#include <cstringt.h>  
...
CString sNumber= "1234567890";
int     nResult;

nResult
= atoi( sNumber );  // automatically does LPCSTR(sNumber)


STL std::string to int

1:
2:
3:
4:
5:
6:
7:
#include <string>
#include <stdlib.h>
...
std
::string sNumber= "1234567890";
int         nResult;

nResult
= atoi( sNumber.c_str() );



Notes:
  • If you are using the UNICODE character set and supplying an output buffer (as with sprintf and itoa) you'll need to keep in mind that characters are two bytes long.  The normal procedure is to declare character buffers as the TCHAR data type, which will take into consideration the data element size.

  • Output buffer length.
    C++ integers are typically 32-bits, with values as high as billions; the range is:
    1:
    2:
    
                     0 to 4,294,967,295 (unsigned)
       
    -2,147,483,648 to 2,147,483,647 (signed)
    Thus, the maximum length of the resulting string is 12 characters (including NULL terminator and not including commas or other formatting). 

    If you are working with 64-bit integers (called __int64 or long long), the values are as high as quintillions; the range is:
    1:
    2:
    
                                 0 to 18,446,744,073,709,551,615 (unsigned)
       
    -9,223,372,036,854,775,808 to  9,223,372,036,854,775,807 (signed)
    Thus, the maximum length of the resulting string is 21 characters (including NULL terminator and not including commas or other formatting).

  • Both sprintf and itoa have been termed unsafe (some would say they've been deprecated, others would not use that term) because of the chance that a sloppy programmer might not provide a large enough output buffer.

    The examples show how to use the safer xxx_s variations of these functions as an alternative.  The older functions might write beyond the end of the buffer and stomp on other variables or blow the stack frame -- and cause endless debugging headaches.  Of course, if you are determined to give yourself grief, you can still blow up the "safe" version by passing in the wrong length value...  

    The CString::Format function allocates the buffer for you and takes care to avoid the buffer overrun problem.  The std::ostringstream << (insertion operator) also takes care of the buffer allocation for you.

  • The examples above compile and work under Microsoft VS2008.  Some Microsoft-specific functionality is implied (refer to the references, below, if you worry about these things).  However, there is an excellent chance that at least one of the variations will work for you in your development system, whatever it is.


References:

atoi, _atoi_l, _wtoi, _wtoi_l
http://msdn.microsoft.com/en-us/library/yd5xkb5c.aspx

sprintf, _sprintf_l, swprintf, _swprintf_l, __swprintf_l
http://msdn.microsoft.com/en-us/library/ybk95axf.aspx

_itoa, _i64toa, _ui64toa, _itow, _i64tow, _ui64tow
http://msdn.microsoft.com/en-us/library/yakksftt(VS.80).aspx

String to Numeric Value Functions  (strtoX, et al.)
http://msdn.microsoft.com/en-us/library/53b7b72e(VS.80).aspx

Data Conversion  (ultoX, etc.)
http://msdn.microsoft.com/en-us/library/0heszx3w(VS.80).aspx

CStringT::Format
http://msdn.microsoft.com/en-us/library/aa314327(VS.60).aspx

ostringstream
http://msdn.microsoft.com/en-us/library/6kacs5y3.aspx

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
If you liked this article and want to see more from this author,  please click the Yes button near the:
      Was this article helpful? 
label that is just below and to the right of this text.   Thanks!
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 


출처 : 
http://blog.naver.com/wassupnari?Redirect=Log&logNo=100107651361  
반응형
Posted by blueasa
, |
C/C++의 Data Type 입니다. 그런데 이것은 OS나 컴파일러에 따라서 차이가 있을 수 있습니다. 가령 16비트OS에서 int 는 16비트이고, 32비트OS에서 int 는 32비트입니다. 여기서는 일반적으로 가장 널리 쓰이는 "비주얼C++ (32비트 버전)"를 기준으로 한 것입니다.

정수 자료형


▶ char, unsigned char          1 byte (8비트)
------------------------------------------------------
char 의 최소값: -128
char 의 최대값: 127

unsigned char 의 최소값: 0
unsigned char 의 최대값: 255 (0xff)



▶ short, unsigned short        2 bytes (16비트)
------------------------------------------------------
short 의 최소값: -32768
short 의 최대값: 32767

unsigned short 의 최소값: 0
unsigned short 의 최대값: 65535 (0xffff)


▶ wchar_t 또는 __wchar_t       2 bytes (16비트)
------------------------------------------------------
wchar_t 의 최소값: 0
wchar_t 의 최대값: 65535

※ wchar_t 는 유니코드 글자 1개를 저장합니다. "unsigned short"과 동일.



▶ int, unsigned int            4 bytes (32비트)
------------------------------------------------------
int 의 최소값: -2147483648
int 의 최대값: 2147483647

unsigned int의 최소값: 0
unsigned int의 최대값: 4294967295 (0xffffffff)



▶ long, unsigned long          4 bytes (32비트)
------------------------------------------------------
long 의 최소값: -2147483648L
long 의 최대값: 2147483647L

unsigned long 의 최소값: 0UL
unsigned long 의 최대값: 4294967295UL (0xffffffffUL)

※ 32비트OS에서의 long 은 int 와 동일



▶__int64 또는 long long        8 bytes (64비트)
------------------------------------------------------
__int64 의 최소값: -9223372036854775808i64
__int64 의 최대값: 9223372036854775807i64

unsigned __int64 의 최소값: 0ui64
unsigned __int64 의 최대값: 18446744073709551615ui64 (0xffffffffffffffffui64)





실수 자료형


▶ float                        4 bytes (32비트)
------------------------------------------------------
가장 작은 양수: 1.175494351e-38F
가장 큰 양수  : 3.402823466e+38F



▶ double                       8 bytes (64비트)
------------------------------------------------------
가장 작은 양수: 2.2250738585072014e-308
가장 큰 양수  : 1.7976931348623158e+308



▶ long double                  8 bytes (64비트)
------------------------------------------------------
double 과 같음.

출처 : http://mwultong.blogspot.com/2006/09/c-char-int-float-data-type-ranges.html
반응형
Posted by blueasa
, |

Libci.lib에 대한 Link 에러 문제이군요.

VS .NET 2003으로 오면서 2002까지 지원하던 '구 버전의 iostream Library'를 더이상 'CRT'에 포함하지 않게 되었습니다.

'구 버전의 iostream Library'가 무엇인고 하니 바로 아래에 나와있는 것들입니다.

LIBCI.lib : Single-thread, Static Link /ML
LIBCIMT.lib : Multithreaded, static link /MT
MSVCIRT.lib : Multithreaded, dynamic link /MD

이것들이 이제 더이상 존재하지 않습니다. C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\lib 경로를 살펴보면 없지요.

'새 버전의 iostream Library'는 다음과 같습니다.

LIBC.lib : Single-threaded, static link /ML
LIBCMT.lib : Multithreaded, static link /MT
MSVCRT.lib : Multithreaded, dynamic link /MD

딱 보니까 이름 짓는 규칙을 아시겠지요? 'i'자가 붙은 게 바로 구형 iostream이고 MS에서 사장시키기로 작정한 것 같습니다. (각 lib의 디버그 버전에는 파일명에 'd'자가 하나씩 더 붙지요.)

원래는 LIBC.lib와 그의 형제들에 구 버전의 iostream이 탑재되어 있었는데, VC++ 4.1 이후부터 iostream을 바꾸고, 기존 것을 계속 쓰고자 하는 사용자를 위해 'i'자를 붙인 Library를 따로 만들어 분리시켜버린 것 같습니다.

말썽을 일으키고 있는 프로젝트와 '인터넷에서 구한 소스' 등이 말썽을 일으키는 것은, 해당 프로젝트에서 구 버전의 iostream을 사용하도록 'Default Library'를 명시적으로 지정하였기 때문이 아닌가 싶네요.

이 문제를 피할려면, 기존 프로젝트의 Default Library를 무시하도록 링커 옵션에서 '모든 기본 라이브러리 무시'를 선택하시거나 '특정 라이브러리 무시' 선택하시기 바랍니다. 이렇게 하면 /NODEFAULTLIB 링커 옵션이 추가됩니다.

이 내용들은 MSDN에 보다 상세하게 나와있습니다.

반응형
Posted by blueasa
, |

LIBCMT.lib(invarg.obj) : error LNK2005: __invoke_watson already defined in MSVCRTD.lib(MSVCR80D.dll)

닷넷 2005에서 .lib를 사용할 때..

디버그용과 릴리즈용을 구분지어줘야 한다.

즉, 프로그램을 디버그 모드인 프로그램에서, 릴리즈 모드로 컴파일 된 lib를 인클루드 할 경우

LIBCMT.lib(invarg.obj) : error LNK2005: __invoke_watson already defined in MSVCRTD.lib(MSVCR80D.dll) 와 같은 링크 에러가 발생한다.

Multi-threaded (/MT) : 릴리즈용

Multi-threaded Debug (/MTd) : 디버그용

DLL도 마찬가지.

반응형
Posted by blueasa
, |
어젠가 그젠가 MSDN 보다가 재미난 문서를 발견했습니다. 안전한 DllMain을 작성하는 방법에 관한 글인데, 이 곳에서 다운로드 받아서 보실 수 있습니다. DLL의 로딩 과정과 로더 락에 관한 설명을 곁들여서 왜 그런 일들이 문제를 일으키는지 자세히 설명해 준답니다. 심심하지 않으신 분들도 꼭 챙겨보세요. ㅋ~ 

아래는 문서 내용 중에 괜찮은 부분 같아서 퍼온 겁니다. 의외로 저런 작업들을 하는 코드를 만나는 경우가 많습니다. 대부분 문제가 발생하지 않더라도 어디선간 문제가 발생하고 있다는 것을 의미하는 거겠죠. 좀 더 자세한 시나리오와 함께 문제를 설명해줬으면 했는데 그런 부분이 없는 것이 약간 아쉽더군요.

경고!!! 
DllMain에서 다음 작업들은 절대로 하지 말 것.

  1. LoadLibrary, LoadLibraryEx 호출. 데드락이나 크래시를 유발한다.
  2. 다른 스레드와 동기화. 데드락을 유발한다.
  3. 로더 락을 획득하려는 코드가 가지고 있는 동기화 오브젝트를 획득하려는 시도. 데드락을 유발한다.
  4. CoInitializeEx를 사용한 COM 스레드 초기화. 특정 조건이 충족될 경우 이 함수는 LoadLibraryEx를 호출한다.
  5. 레지스트리 함수들. 이 함수들은 advapi32.dll에 구현되어 있다. advapi32.dll이 초기화 되지 않았다면 크래시가 발생할 수 있다.
  6. CreateProcess 호출. 프로세스 생성은 다른 DLL을 로드할 수 있다.
  7. ExitThread 호출. DLL 디태치(detach) 과정 중에 스레드를 종료하면 로더 락을 다시 획득하도록 만들 수 있다. 이는 데드락이나 크래시가 유발된다.
  8. CreateThread 호출. 동기화만 하지 않는다면 스레드 생성은 괜찮을 수 있다. 하지만 위험하다.
  9. 네임드 파이프나 네임드 오브젝트 생성 (2000만 해당한다). 윈도우 2000에서 네임드 오브젝트 생성은 터미널 서비스 DLL에서 구현되어 있다. 해당 DLL이 초기화되어 있지 않다면 크래시.
  10. CRT에 포함된 메모리 관리 함수들. CRT DLL이 초기화되어 있지 않다면 크래시.
  11. user32.dll이나 gdi32.dll에 포함된 함수 호출. 일부 함수들은 다른 DLL을 로드하고, 이 사실은 크래시가 발생할 수 있다는 것을 의미한다.
  12. 관리된 코드 사용.
* 가장 아름다운 DllMain은 존재하지 않는 것이다 (비어 있는 함수 바디).
** 그래도 먼가 하고 싶다면 kernel32.dll에 포함된 함수 중에 위에서 언급되지 않은 것들만 쓰도록 한다. kernel32.dll이 초기화는 운영체제가 보장해 준다. 
*** 글로벌 오브젝트에 대한 초기화 코드 또한 DllMain 과정에 포함된다. 따라서 글로벌 오브젝트의 생성자 내지는 초기화 함수 부분에 위에서 언급한 내용이 있어서는 안된다.
**** 초기화를 하지 말란 소린가? 아니다. 지연시키라는 말이다.

요 근래엔 정말 컴터 책은 한 권도 안 읽은 것 같네요. 참신한 책 있으면 추천 좀 해주세용. 《실용주의 프로그래머》나 《The Art Of Unix Programming》을 보면서 흘렸던 눈물이 그립군요. 그나마 제프리 아저씨의 신간이 있었지만, 그마저도 사실 전 전판에 비해서 큰 차이를 보기는 힘들었던 것 같습니당.

출처 : http://www.jiniya.net/tt/788
반응형
Posted by blueasa
, |

strncmp 와 memcmp

Programming/C/C++ / 2011. 7. 14. 14:07

중간에 NULL 이 포함되면, 그 뒤의 내용이 틀려도 strncmp는 같다고 생각합니다.

"strcmp\0abc" , "strcmp\0123" 을 strncmp는 같다고 생각하지만

memcmp 로 위의 10 바이트를 검사하면 틀리다고 나옵니다.

이건 str 계열의 함수가 중간에 NULL을 만나면 종료하기 때문입니다.


출처 :  http://kldp.org/node/29

반응형
Posted by blueasa
, |
설명

double형 나눗셈의 나머지를 구합니다. 변수형에 따라 아래와 같은 함수가 준비되어 있습니다.

변수 타입 함수 헤더파일

double

fmod( double x, double y) math.h
float fmodf( float x, float y) math.h
long double fmodl(long double x, long double y) math.h
헤더 math.h
형태 double fmod( double number, double denom);
인수 double number 피제수, 나누어 지는 수
double denom 제수, 나누는 수
반환 double 나머지
예제
#include <stdio.h>
#include <stdlib.h>

int main( void)
{
   printf( "%g / %g 의 나머지 %gn", 123.123, 12.12, fmod( 123.123, 12.12));

   return 0;
}

]$ ./a.out 123.123 / 12.12 의 나머지 1.923 ]$


반응형
Posted by blueasa
, |
실수는 정수부(Integer Parts)와 소수부(Fractional Parts)로 이루어져 있습니다.

123.456789555 라는 실수에서

123 이 정수부이고

.456789555 가 소수부입니다. 정수부와 소수부를 분리하여 얻는 함수가

math.h 헤더 파일의

double modf(double x, double *ipart);

입니다. 소수부는 직접 반환하고, 정수부는 ipart 에 정수가 아닌 실수형으로 넣습니다.


정수부/소수부 분리, 소수점 이하만 구하는 함수 예제: modf() Function Example


파일명: 0.cpp
#include 
#include 


int main(void) {

  double integer, fraction;
  double n = 123.456789555;

  fraction = modf(n, &integer);

  printf("%.9f = %.f + %.15f\n", n, integer, fraction);


  return 0;
}


integer 변수에 정수부가 들어가는데 정수형이 아닌 실수형으로 들어갑니다. 그래서 %.f 이런 포맷 지정자를 사용하여 정수로 출력했습니다.

fraction 변수에는 소수부가 들어갑니다.


컴파일 및 실행 결과:
D:\Z>cl /nologo 0.cpp && 0.exe
0.cpp
123.456789555 = 123 + 0.456789555000000

D:\Z>

정수부와 소수부가 나누어졌습니다.

그런데 소수부가 그리 정밀하게 구해지지는 않았습니다.





modf 함수 없이, 실수에서 소수부 구하기


다음과 같이 할 수도 있습니다:
#include 
 
int main(void) {

  double n = 123.456789555;

  printf("%.9f = %d + %.15f\n", n, (int) n, n - (int) n);

  return 0;
}
[출처] http://mwultong.blogspot.com/2006/12/c-get-fractional-part-only.html


처 : 
http://sunnmoon.egloos.com/2218722
반응형

'Programming > C/C++' 카테고리의 다른 글

strncmp 와 memcmp  (0) 2011.07.14
fmod double형 나눗셈의 나머지 구하기  (0) 2011.03.24
이름공간(namespace)의 함정.  (0) 2011.03.13
카메라 흔들기  (0) 2011.03.05
[게임코드]손쉽게 카메라 흔들기  (0) 2011.03.04
Posted by blueasa
, |