IT 취미생활.  
Front Page
Tag | Location | Media | Guestbook | Admin   
 
'C++'에 해당하는 글(10)
2009.09.10   Hex String to integer 1
2009.07.01   [warning]suggest parentheses around assignment used as truth value
2009.06.18   소스안에 적당한 라인 수
2008.10.17   [알고리즘] Selection Sort
2008.10.16   [알고리즘] BubbleSort
2008.09.01   [C++]asio C++ library
2008.03.12   Tiny singleton helper class
2008.03.10   간단한 Callback Function 예제
2008.03.10   [펌]Tiny singleton helper class
2008.03.09   2차 배열 동적 할당 - 일반 및 개선 2


Hex String to integer

이전에 포스팅한 GetProfileToString을 통해서, 특정 값을 읽어왔는데 제기럴 Hex 값이었다.
Int 값이었으면 atoi를 이용해서 int로 쓰겠는데 왠걸 hex string... 열심히 구글링 해보니 CodeProject에 Sample이 있어 업어왔다.


linux에서 왜 string.h에 strupr이 없는걸까???????
보안에 문제가 있는 API라서? 쩝....

Set로 움직이는 함수입니다.
꼭 필요한 분들이 있을 것 같습니다.

수정사항이 있으시면 언제든지!!!  피드백 부탁 드립니다.

고운하루 되세요


char* StrUpr( char *str )
{
    int loop = 0;
    while( str[loop] != '\0' )
    {
        str[loop] = (char) toupper( str[loop] );
        loop++;
    }
    return str;
}


/*
 * hex string to int
*/

int xtoi(char *value)
{
    struct CHexMap
    {
        char chr;
        int value;
    };

    const int HexMapL = 16;
    CHexMap HexMap[HexMapL] =
    {
        {'0', 0}, {'1', 1},
        {'2', 2}, {'3', 3},
        {'4', 4}, {'5', 5},
        {'6', 6}, {'7', 7},
        {'8', 8}, {'9', 9},
        {'A', 10}, {'B', 11},
        {'C', 12}, {'D', 13},
        {'E', 14}, {'F', 15}
    };

    /* remove space */
    int len = strlen(value);
    for(int i = 0; i < len; i++) {
        if( *(value+i) == ' ') {
            value++;
        } else {
            break;
        }
    }

    /* alloc buffer and change upper */
    char *mstr = StrUpr(strdup(value));
    char *s = mstr;
    int result = 0;
    if (*s == '0' && *(s + 1) == 'X')
        s += 2;
    bool firsttime = true;
    while (*s != '\0')
    {
        bool found = false;
        for (int i = 0; i < HexMapL; i++)
        {
            if (*s == HexMap[i].chr)
            {
                if (!firsttime) result <<= 4;
                result |= HexMap[i].value;
                found = true;
                break;
            }
        }
        if (!found) break;
        s++;
        firsttime = false;
    }
    free(mstr);
    return result;
}



[warning]suggest parentheses around assignment used as truth value

워닝 발생

if ( x = getSomethingValue())
{
 ........
}

해결방법
if ( (x = getSomethingValue()) )
{
 ........
}

KIN.....



소스안에 적당한 라인 수
기능별로 파일을 분리하는 것이 가장 적당할 것 같은데...

"보통 1000라인 이하가 적당하다" 라고 합니다.
(코드 컴플릿에서도 관련 내용을 다루고 있는데
기억이 가물한지라.. 확인 후 내용 추가...)


클래스를 한 헤더에 여러개 쓰면 소스가 커지는 원인이므로
완전 밀접한 작은넘(클래스) 아니면.. 클래스당 하나의 모듈로 나눈다.

낙서질
 
스르르르륵


[알고리즘] Selection Sort

프로그래밍 불여일타!!의 프로젝트의 일환으로, 퇴근후 배깔고 하는 알고리즘 공부를 시작!!
그 결과물로 간단 간단한 알고리즘을 작성하고, Blog에 올리기로 했습니다.

오늘은 간단하게 Selection Sort를 만들어 보았습니다.

* 원리는 : 총 1...n개의 정렬 되지 않은 요소에서, 첫번째 놈을 가져다가 가장 작은 값을
              가진다라 가정 하고  나머지 n-1개와 비교를 하게 합니다. 그래서 그중 가장
              작은 녀석을 기억 하고 있다가, 1번째 자리와 바꿉니다. 그리고 index을 하나 더
              증가 해서 두번째 요소를 가지고  n-2 만큼 loop를 돌아서 다시 최소값을 찾고
              바꿔 줍니다. 이렇게 반복하면 정렬이 됩니다.( 사실 그림으로 보면 아무것도
              아닙니다. 그림은 귀찮아서 안그렸습니다.)

* 성능 :  O(N^2)

* 코드

void swap( int *a, int *b )
{
     int dump = *a;
     *a = *b;
     *b = dump;
}

void SelectionSort( int *_arrayBuffer, const unsigned int _arraySize )
{
     for( int i = 0; i < _arraySize; i++ )
     {
          int nMinIndex = i;
          for( int j = i + 1; j < _arraySize; j++ )
          {
               if( _arrayBuffer[j] < _arrayBuffer[nMinIndex] )
               {
                   nMinIndex = j;
               }
          }
          swap( _arrayBuffer[nMinIndex], _arrayBuffer[ i ] );
      }  
}


[알고리즘] BubbleSort

간단하게 Bubble Sort을 만들어 보았습니다.

정렬 방식은 Buffer 마지막에 가장 큰 값을 옮겨두고, 첫 번째 for loop의 index를 -- 하여
뒤에서 부터 큰 값들이 정렬되도록 하는 sorting 방법입니다.
알고리즘 효율은 O(N^2) 입니다.

Function 이름은 "한눈에 보이는 C 알고리즘"이라는 책에서 가져다 사용 했습니다. - 귀차니즘

프로그래밍의 왕도는 역시 불여일타!!!!





#include <cstdlib>
#include <iostream>

using namespace std;


#define MAX_SIZE 100

int NumberExit( int *_arrayBuffer, int _number, int _index)
{
    for( int i=1 ; i < _index; i++ )
    {
            if( _arrayBuffer[i] == _number )
            {
                return true;
            }
    }
    return false;
}

void MakeRendomNumber( int *_arrayBuffer )
{
     int nNum = 0;
     srand( (unsigned)time( NULL ) );
     _arrayBuffer[0] = MAX_SIZE;
     int i = 1;
     while( i < MAX_SIZE )
     {
            nNum = rand() % MAX_SIZE;
            if( false == NumberExit( _arrayBuffer, nNum, i ))
            {
                _arrayBuffer[i] = nNum;
                i++;
            }
     }
}

void DisplayBuffer( int *_arrayBuffer )
{
     for( int i = 0; i < MAX_SIZE; i ++ )
     {
          if( (i % 10) == 0 )
          {
              cout << "\n";
          }
          cout << _arrayBuffer[i] << "\t";
     }
     cout << "\n";
}


 

void BubbleSort( int *_arrayBuffer, const unsigned int _arraySize )
{
     for( int i = _arraySize - 1; i >= 0; i-- )
     {
          for( int j = 1; j <= i ; j++ )
          {
               if( _arrayBuffer[ j - 1 ] > _arrayBuffer[ j ] )
               {
                   int nDummy  = _arrayBuffer[ j - 1 ];
                   _arrayBuffer[ j - 1 ] = _arrayBuffer[ j ];
                   _arrayBuffer[ j ] = nDummy;
               }
          }
     }
}

int main(int argc, char *argv[])
{
    int Buffer[ MAX_SIZE ] = { 0 };
   
    MakeRendomNumber( Buffer );
    DisplayBuffer( Buffer );
    cout << "\n";
   
    BubbleSort( Buffer, MAX_SIZE );
    cout << "\n";
    DisplayBuffer( Buffer );
   
    system("PAUSE");
       
    return EXIT_SUCCESS;
}



[C++]asio C++ library
크로스 플렛폼 C++ 라이브러리로써 네트워크와 저수준 I/O를 비동기 모델로 제공한다.


asio is a cross-platform C++ library for network and low-level I/O programming that provides developers with a consistent asynchronous model using a modern C++ approach.

Download
asio - 1.2.0 (Stable)
Last Update: Aug 14 2008



SourceForge.net을 가다 보면 나름 좋은 프로그램들을 만날 수 가 있다.

그럼 고운하루 되세요

 



Tiny singleton helper class

Introduction

Sometimes we have to code with 'singleton'. If you don't know what Singleton is, you can read about it in many Design Pattern books. Singleton principle is really simple.

As you know, if you use reference pointer for singleton object, then you must delete it when program terminates. But it will be good because it does 'late instance'.

I want to terminate singleton object automatically, and instance lately. So, I coded this.

Good things:

  • Late instance.
  • Safe terminate automatically.
  • Separated code for Object and Singleton.

Here is my tiny singleton helper class - CSingletonT<>, and I hope it helps you.

//
// Using singletonT class
//
#include "SingletonT.h"
// test class
class CObj
{
protected:
    CObj(){ x = 0 ; TRACE("Created CObj\r\n"); }
public:
    virtual ~CObj(){ x = 0 ; TRACE("Deleted CObj\r\n");}
    int x;
};
// Testing
void CTestSingleTDlg::OnButton1()
{
    // TODO: Add your control notification handler code here
    // if first call, then singleton object will instance ( instance lately )
        CObj* o = CSingletonT<CObj>::GetObject();
    // use singletone object
    o->x ++;
    TRACE("o->x = %d\r\n",o->x);
}
------------------------------------------------------------------------------------
싱글톤에 조금은 벗어났지만,활용 할 수 있는 방법은 많다고 생각 됩니다.
원문을 보고 싶으시다면  아래로...
정확한 출처는 CodeProject 입니다.



http://www.codeproject.com/cpp/singlet.asp
우리 나라 분이 작성한 글입니다


간단한 Callback Function 예제
간단한 Callback 예제 C / C++

2007/07/28 08:35

복사 http://blog.naver.com/liezzang99/40329125

// TestCallbackFunction.cpp : Defines the entry point for the console application.
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


#define BOOL unsigned int
#define TRUE 1
#define FALSE 0

typedef BOOL (*RonieTest_Callback)( int nValue );

typedef struct
{
 int number;
 char *name;
 RonieTest_Callback bCount_CB;
} WmMyInfo;


BOOL fnConditionCallback_cb( int nValue )
{
 BOOL bRet = 0;
 if( 0 == (nValue % 2) )
 {
   bRet = 1;
 }
 return bRet;
}


WmMyInfo *TestLoopFunction( WmMyInfo *pInfo )
{
 while(1)
 {
  pInfo->number++;
  if( pInfo->number == 10 )
  {
   BOOL bRet = pInfo->bCount_CB( pInfo->number );
   if( bRet == TRUE )
   {
    pInfo->name = new char[5];
    memset( pInfo->name, 0, sizeof(char)*5 );
    strncpy( pInfo->name, "Even", strlen("Even") );
    return pInfo;
   }

   return  pInfo;
  }
 }
}


int main(int argc, _TCHAR* argv[])
{
 WmMyInfo *pMyInfo = new WmMyInfo;
 pMyInfo->number = 0;
 pMyInfo->bCount_CB = fnConditionCallback_cb;

 pMyInfo = TestLoopFunction( pMyInfo );

 printf( "Number : %s", pMyInfo->name );


 delete []pMyInfo->name;
 delete pMyInfo;

 return 0;
}



[펌]Tiny singleton helper class

Introduction

Sometimes we have to code with 'singleton'. If you don't know what Singleton is, you can read about it in many Design Pattern books. Singleton principle is really simple.

As you know, if you use reference pointer for singleton object, then you must delete it when program terminates. But it will be good because it does 'late instance'.

I want to terminate singleton object automatically, and instance lately. So, I coded this.

Good things:

  • Late instance.
  • Safe terminate automatically.
  • Separated code for Object and Singleton.

Here is my tiny singleton helper class - CSingletonT<>, and I hope it helps you.

//
// Using singletonT class
//
#include "SingletonT.h"
// test class
class CObj
{
protected:
    CObj(){ x = 0 ; TRACE("Created CObj\r\n"); }
public:
    virtual ~CObj(){ x = 0 ; TRACE("Deleted CObj\r\n");}
    int x;
};
// Testing
void CTestSingleTDlg::OnButton1()
{
    // TODO: Add your control notification handler code here
    // if first call, then singleton object will instance ( instance lately )
        CObj* o = CSingletonT<CObj>::GetObject();
    // use singletone object
    o->x ++;
    TRACE("o->x = %d\r\n",o->x);
}
------------------------------------------------------------------------------------
싱글톤에 조금은 벗어났지,활용 할 수 있는 방법은 많다고 생각 됩니다.
원문을 보고 싶으시다면  아래로...
http://www.codeproject.com/cpp/singlet.asp
우리 나라 분이 작성한 글입니다.


2차 배열 동적 할당 - 일반 및 개선
일반 적인 2차 배열 동적 할당


코드:
template <typename Ty>
Ty **alloc2DArray(int width, int height)
{   
 Ty **arr = new Ty*[height];   
 for(int i=0; i<height; i++)   
 {       
  arr[i] = new Ty[width];  
 }   
 return arr;
}
template <typename Ty>
void free2DArray(Ty **&arr, int height)
{  
 for(int i=0; i<height; i++)   
 {       
  delete []arr[i];       
  arr[i] = 0;   
 }  
 delete []arr;   
 arr = 0;
}


고급
int **imatrix( int w, int h ) 
{
 int i;
 int **m;
 m = new int * [h]; 
 if( !m )
  PutError("memory alloc failure in imatrix()"), exit(0);
 m[0] = new int [ w * h ]; 
 if( !m[0] )
  PutError("memory alloc failure in imatrix()"), exit(0);
 for( i = 1; i < h; i++ ) { 
  m[i] = &m[0][ i * w ];
 }
 return m;
}

고급으로 할당 하는 방법에 대해서 눈여겨 보세요.


BLOG main image
취미생활
 Notice
 Category
분류 전체보기 (191)
매일매일갱생 (83)
서버개발 (1)
임베디드개발 (12)
Programming (80)
Personal Projects (6)
유용한 프로그램 (0)
 TAGS
Algorithm 티스토리 초대장 MP3 벨소리 변경 M480 isdbt 개발자 Linux debugging 서태지 It 음식 1seg DirectShow C++ DVB warning Brazil 알고리즘 english email 티스토리초대 spam mail Error Case VC++ project 군대 영어 이메일 Debug 출장 Windows Mobile6.0 퇴사 ISDB-T C Java English Dshow Wince5.0 미라지폰 DVB-T
 Calendar
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
 Recent Entries
 Recent Comments
 Recent Trackbacks
 Archive
 Link Site
zextor
괴짜 프로그래머의 일상사~@@
Gag & Peace, and more..
Kazakhstan Almaty.......
Min-A
Sadgarret
Steve Yoon's log
가슴 뛰는 삶을 살아라
오스틴 파워
GUI sin
melanie parker_Lady
제레미의 TV 2.0 이야기..
 Visitor Statistics
Total :
Today :
Yesterday :
rss