#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <iostream>
#include <iomanip>
#include "awgn.h"

using namespace std;
// fixed-point header file
// Qm.f
// m: the number of bits for integer
// f: the number of bits for fraction 

typedef signed short fx_t;

#define M 3  // m
#define F 2  // f



#define F_MAX ( ( 1 << (M+F) ) - 1 )
#define F_MIN ( -1 * ( 1<<(M+F) ))
#define Fl2Fx(x) (fx_t) (x >= 0) ? ( (x * (1 << F)) + 0.5 ) : ( (x * (1 << F)) - 0.5 )    //floating to fixed-point (using integer)
#define Fx2Fl(x)  (((float)x)/(1 << F))


fx_t sat_check(fx_t x)
{
    if (x > F_MAX)
        return F_MAX;
    else if (x < F_MIN)
        return F_MIN;
    else
        return x;
}

int main(void){

    float R = 0.5;
    double snr = 3.0;
    double sigma;

    double max = 0;


    const int N = 100; //length

    float sample[N] = { 0 };
    fx_t f_sample[N] = { 0 };  //fixed point
    fx_t q_sample[N] = { 0 };  // quantized

    int q_bit = 4; // the number of bit for quatization
    int q_max = pow(2, q_bit) - 1;

    //fixed-point 에서의 maximum 값, overflow 처리 필요.

    cout << "Max. Fixed-Point :" << F_MAX << endl;
    cout << "Min. Fixed-Point :" << F_MIN << endl;
    //getchar();
    sigma = pow(10, -0.05*snr) / sqrt(2 * R);

    //cout << "Orig.\t\tFixed\t\tFx_int\t\tFx_fl" << endl;
    for (int i = 0; i < N; i++)
    {
        float temp;
        sample[i] = 1 + gaussian(0, sigma);

        f_sample[i] = Fl2Fx(sample[i]);
        //temp = (int)(sample[i] * (1 << F));
        //temp = (float)temp / (1 << F);
        //cout << setw(8) << sample[i] << "\t" << temp << "\t\t";

        //printf("%d\t\t", f_sample[i]);
        //printf("%f\n", Fx2Fl(f_sample[i]));
        //putchar('\n');
    }
    cout << "F_samp\t\tOrig.\t\tSat" << endl;
    fx_t temp = 0;
    for (int i = 0; i < N; i++)
    {

        temp += f_sample[i];
        cout << f_sample[i]<<"\t\t"<<temp << "\t\t" << sat_check(temp) << endl;
        getchar();
    }
    cout << endl;
    cout << "maximum:  " << max << endl;

    return 0;
}

fixed_point_proto.md


'C and C++' 카테고리의 다른 글

Fixed-point in C/C++  (0) 2016.04.05
main function arguments  (0) 2016.03.11
OpenMP in Macbook  (0) 2016.03.10
OpenMP  (0) 2016.03.09
C언어 최적화 기법  (0) 2016.02.05

fixed-point in C

original material: artist-embedded.org/EmbeddedControl Slides
reference 1: fixedpt.html
reference 2: Q_format

1. Fixed-point Representation

  • x: real number
  • X: fixed-point number
  • N: wordlength
  • m: integer (excluding sign bit)
  • f: number of fraction bit
  • “Q-format” : Qm.n
0/1101/011
sign bit/4bit integer/3bit fraction

2. Conversion to and from fixed-point

  • real to fixed

    • Multiply the floating point number by 2^f
    • Round to the nearest integer

      X=round(x˙2f)

  • fixed to real

    x=X˙2f

example) 13.4 to Q4.3 format

X=round(13.4˙23)=107(=011010112)

3. Range of fixed-point representation

  • negative number: 2’s complement

    • N=8, 2^(-8) ~ 2^(8-1)
      binary representation decimal
      00000000 0
      00000001 1
      00000010 2
      01111111 127
      10000000 -128
      10000001 -127
      11111111 -1
  • range of Qm.f [ref]

    [2m,2m2f]

4. Arithmetic operations of fixed-point

  • Satuation check
int16_t sat16(int32_t x)
{
    if (x > 0x7FFF) return 0x7FFF;
    else if (x < 0x8000) return 0x8000;
    else return (int16_t)x;
}
  • Addition
int16_t q_add_sat(int16_t a, int16_t b)
{
    int16_t result;
    int32_t tmp;

    tmp = (int32_t)a + (int32_t)b;
    if (tmp > 0x7FFF)
        tmp = 0x7FFF;
    if (tmp < -1 * 0x8000)
        tmp = -1 * 0x8000;
    result = (int16_t)tmp;

    return result;
}
  • Subtraction
int16_t q_sub(int16_t a, int16_t b)
{
    int16_t result;
    result = a - b;
    return result;
}
  • Multiplication
// precomputed value:
#define K   (1 << (f - 1))    // f: fraction of fixed-point

int16_t q_mul(int16_t a, int16_t b)
{
    int16_t result;
    int32_t temp;

    temp = (int32_t)a * (int32_t)b; // result type is operand's type
    // Rounding; mid values are rounded up
    temp += K;
    // Correct by dividing by base and saturate result
    result = sat16(temp >> Q);

    return result;
}
  • Division
int16_t q_div(int16_t a, int16_t b)
{
    int16_t result;
    int32_t temp;

    // pre-multiply by the base (Upscale to Q16 so that the result will be in Q8 format)
    temp = (int32_t)a << Q;
    // Rounding: mid values are rounded up (down for negative values).
    if ((temp >= 0 && b >= 0) || (temp < 0 && b < 0))
        temp += b / 2;
    else
        temp -= b / 2;
    result = (int16_t)(temp / b);

    return result;
}

'C and C++' 카테고리의 다른 글

Fixed Point Prototype  (0) 2016.04.09
main function arguments  (0) 2016.03.11
OpenMP in Macbook  (0) 2016.03.10
OpenMP  (0) 2016.03.09
C언어 최적화 기법  (0) 2016.02.05

main 함수의 argument

#include <stdio.h>

int main(int argc, char* argv [])
{
    printf("num_of_param: %d, program_name: %s", argc, argv[0]);
}

참고자료

프로그램을 실행할 때 인자를 받아와서 프로그램에서 사용할 수 있다. scanf로 받아오는 것으로 짜려고 했더니 bash script 로 여러 번 실행할 수가 없어서 다시 써볼까 싶어 찾아봤는데, 하도 오래 전에 써본 터라 기억이 제대로 나지 않았다. 공부한 김에 메모하는 것으로.

위의 프로그램을 컴파일하고 아무런 인자도 넣지 않은 채 실행하면 다음과 같은 결과를 볼 수 있다.

num_of_param: 1, program_name: ./b.out

ps. b.out은 컴파일 후 생성된 실행파일이다.

이 예제를 통해 메인함수는 기본적으로 프로그램 이름을 하나의 인자로 가진다는 것을 알 수 있다.

문제는 이렇게 받아오는 인자가 문자열이라는 것.

가장 단순한 해결방법으로는 묵직한 atoi함수를 사용하는 방법이다.

일단 실험이 급하니 이것부터 이용해서 해볼까 싶다.

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

int main(int argc, char *argv[])
{

    printf("input was %d and %d", atoi(argv[1]), atoi(argv[2]) );

    return 0;

}

위 코드를 컴파일한 후 $>a.out 1 2 이렇게 실행하면 다음과 같은 결과를 볼 수 있다.

input was 1 and 2

'C and C++' 카테고리의 다른 글

Fixed Point Prototype  (0) 2016.04.09
Fixed-point in C/C++  (0) 2016.04.05
OpenMP in Macbook  (0) 2016.03.10
OpenMP  (0) 2016.03.09
C언어 최적화 기법  (0) 2016.02.05

맥북에서 openmp를 돌리기 위해서는 좀 귀찮은 과정이 필요하다. (Visual Studio의 경우 기본적으로 포함되어 있다.)

XCode7 에서는 OpenMP 지원을 하지않기 때문에  

우선 homebrew설치 진행

터미널에서 아래의 코드를 실행하면 된다. (http://wooriworld2006.tistory.com/308)


ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"




나머지 설치 과정은 아래의 스택오버플로우를 참조...

http://stackoverflow.com/questions/33668323/clang-omp-in-xcode-under-el-capitan


2. homebrew를 이용해 openMP 설치

>>brew install clang-omp


3. X code  프로젝트 생성

4. User defined setting 에 CC 항목 추가 한 후  /usr/local/bin/clang-omp 추가

5. Other C flags 항목에 -fopenmp 추가

6. Header Search Path에 /usr/local/include 추가

7. Enable Modules (C and Objective-C) 를 No로 변경하기

8. Build Phases 에서 Link Binary With Libraries 에 /usr/local/lib/libiomp5.dylib 추가

9. symbolic link 추가 (터미널에서 다음 실행)

sudo ln -s /usr/local/bin/clang-omp++ /usr/local/bin/clang++-omp

10. 소스코드에 omp.h 헤더 include

#include "libiomp/omp.h"


===================================================================================

XCode에서 릴리즈한 아이가 제대로 동작하지 않아 gcc++5 를 이용한 방법을 찾아냈다.

http://mathcancer.blogspot.kr/2016/01/PrepOSXForCoding-Homebrew.html


- gcc5 설치 시 make bootstrap 과정에서 꽤나 오랜 시간이 걸리므로 쫄지말자.







'C and C++' 카테고리의 다른 글

Fixed-point in C/C++  (0) 2016.04.05
main function arguments  (0) 2016.03.11
OpenMP  (0) 2016.03.09
C언어 최적화 기법  (0) 2016.02.05
걸음마  (0) 2015.12.08

1.

Visual Studio에서 OpenMP 프로그래밍을 한다면, 프로젝트 옵션에서 openMP 활성화를 해주는 것을 잊지 말자.ㅠ

프로젝트 속성> Configuration Properties> C/C++ > Language > Open MP Support "Yes (/openmp)"





2.

난수를 생성하는 부분은 병렬화를 고려한 랜덤함수를 쓰지 않는 한 병렬화하지 않도록 하자.



'C and C++' 카테고리의 다른 글

main function arguments  (0) 2016.03.11
OpenMP in Macbook  (0) 2016.03.10
C언어 최적화 기법  (0) 2016.02.05
걸음마  (0) 2015.12.08
Fixed point with C++  (0) 2015.12.08

http://www.joinc.co.kr/modules/moniwiki/wiki.php/Site/C/Documents/COptimization


몇몇개는 지금은 해당되지 않는 것도 있지만, 

꽤나 설득력 있는 것들도 많은 것 같다.


기왕 시뮬레이터를 손대기로 한 것이니, 조금씩 더 개선해보자.

'C and C++' 카테고리의 다른 글

OpenMP in Macbook  (0) 2016.03.10
OpenMP  (0) 2016.03.09
걸음마  (0) 2015.12.08
Fixed point with C++  (0) 2015.12.08
C++ , 객체지향  (0) 2015.12.08

#include <iostream>


int main(void){

std::cout << "Hello world!" << std::endl;

std::cout << 1 << 'a' << "String" << std::endl;

return 0;

}


strcat 같은 함수가 필요없구나.

예제코드 다 코딩하기 보다는 연습문제 풀면서 공부하자.


연습문제 


1-1-1


#include <iostream>


int main(void){

int in[10];

int sum = 0;

for (int i = 0; i < 10; i++)

{

std::cout << i + 1 << "번째 수 입력:";

std::cin >> in[i];

sum += in[i];

}

std::cout << "합계: " << sum << std::endl;


return 0;

}


1-1-2 

#include <iostream>


int main(void){

char name[50];

char phone[15];


std::cout << "Name: ";

std::cin >> name;


std::cout << "Phone#: ";

std::cin >> phone;


std::cout << "Name : " << name << std::endl << "Phone Number: " << phone << std::endl;


return 0;

}

String 따로 배우면 또 달라지겠지


1-1-3

#include <iostream>


int main(void){

int input;


std::cout << "Number: ";

std::cin >> input;

for (int i = 1; i < 10; i ++)

std::cout << input << " X " << i << " = " << input*i << std::endl;


return 0;

}







'C and C++' 카테고리의 다른 글

OpenMP in Macbook  (0) 2016.03.10
OpenMP  (0) 2016.03.09
C언어 최적화 기법  (0) 2016.02.05
Fixed point with C++  (0) 2015.12.08
C++ , 객체지향  (0) 2015.12.08

LDPC Decoder를 C++로 뜯어고치기 프로젝트를 들어가기로 했다.


괜히 fixed point가 가능한 라이브러리들을 찾아보았는데 링크를 그냥 날려버리기 뭣해서 블로그에 정리해둔다.


http://stackoverflow.com/questions/2945747/c-fixed-point-library

이 글에 다양한 링크들이 있는데 몇가지 추리자면,


http://www.codeproject.com/Articles/37636/Fixed-Point-Class


https://alikhuram.wordpress.com/2013/05/20/implementing-fixed-point-numbers-in-c/

'C and C++' 카테고리의 다른 글

OpenMP in Macbook  (0) 2016.03.10
OpenMP  (0) 2016.03.09
C언어 최적화 기법  (0) 2016.02.05
걸음마  (0) 2015.12.08
C++ , 객체지향  (0) 2015.12.08

C++ 공부자료는 윤성우 라는 분의 열혈강의 프로그래밍,

그리고 각종 블로그들이다.

우선 메인으로 보는 블로그는 바로 여기.

http://wkdghcjf1234.blog.me/220387088319


C++은 학부시절 들을 기회가 있었는데, 수강신청을 실패했고, 증원되지 않아서 결국 듣지 못했다.

전공 시간에 억지로 과제라도 하면서 익혔으면 지금 공부하는데 훨씬 더 마주하기가 쉬웠을텐데.. 하는 아쉬움이 남지만, 그래도 어쩌겠는가.

'가장 빠른 때가 지금이다'라는 말도 있지 않는가. 


무튼 지나간 날은 모두 뒤로 하고, 다가올 객체 지향을 향해 할로 해보자.


객체지향이라는 말은 소프트웨어 공학 시간에 UML을 배우면서 처음으로 제대로 듣게 되었는데, 그때도 역시 제대로 이해되지 않았다.

왜냐하면.. 객체지향이라고 하더라도 결국 프로그램이 순서대로 실행되는거 아닌가 하는 게 가장 걸렸기 때문이다. 

뭐가 다른거지..? 왜 따로 부르지..?


AVR 강의를 하러 갔을 때 수강생 중 한명이 면접을 보러 갔더니 객체지향과 절차지향에 대해 설명하라고 했단다.

처음 객체지향이라는 말을 들은지 한참이나 지났음에도 아직 이해를 못하고 있었던 터라, 연구실로 돌아와 동료 형에게 물어보았다.


연구실 형도 처음에는 절차지향과 상반되는 식으로 객체지향을 설명하자 석연치 않아 하셨다. 

그래서 포풍 검색 끝에 정말 잘 정리되어 있는 포스팅 하나를 발견했다.

http://blog.naver.com/atalanta16/220249264429

요약하자면, 객체지향과 절차지향은 프로그래밍 언어의 특성을 나타낸 것이라기 보다는,

개발을 하는 방법의 특성에 따라 분류하는 것이라는 것.

객체 지향 프로그래밍을 한다고 하더라도 절차대로 하지 않는다는 뜻이 절대 아니라는 것.

명심하며 공부를 시작해보자.


'C and C++' 카테고리의 다른 글

OpenMP in Macbook  (0) 2016.03.10
OpenMP  (0) 2016.03.09
C언어 최적화 기법  (0) 2016.02.05
걸음마  (0) 2015.12.08
Fixed point with C++  (0) 2015.12.08

+ Recent posts