단위의 개념

이번 포스팅에서는 Qt 프로그램 구현 시 시간이나 전압 단위를 변환하는 방법에 대해 설명드리겠습니다.
단위란 어떤 물리량이나 수량의 크기의 기준을 말하는데, 국제단위계에서는 시간, 길이, 질량, 전류 등  7개의 기본 단위가 정의되어 있습니다.

 

시간의 단위에서 1ms 는 1/1000초, 1us는 1/1000000초, 1ns는 1/1000000000초의 값을 가지고 ,

단위에 따른 양의 차이를 기준으로 각 단위별 값을 나타내면 아래와 같습니다.

1s = 1000ms = 1000000us = 1000000000ns (시간)

1m = 1000mm = 1000000um = 1000000000nm (길이)

1g = 1000mg = 1000000ug = 1000000000ng (질량)

1V = 1000mV = 1000000uV = 1000000000nV (전압)

...

 

프로그램을 만들다보면 다양한 입력값에 따라서 단위를 제어해야 할 경우가 생기는데,

예를 들어 시간 단위에서 0.000003s, 0.003ms, 3us는 모두 동일한 값이고, 전압 단위에서 3V, 3000mV, 3000000uV도 동일한 값입니다.

각 단위의 양의 크기를 쉽게 나타내기 위해 SI 접두어가 사용된 것 입니다.

 

위 예시의 경우 사용자가 입력하는 시간이나 전압의 입력값은 다르지만 단위 변환 후, 결과값은 모두 같다는 점입니다.

이 때 프로그램의 동작에 따라 각각의 단위를 변환하여 값을 비교해 단위에 따라 계산을 해주어야 합니다.

 

프로그램 구현

초 입력시 모두 Sec로, 전압 입력시 V로 단위를 변환하는 예제를 구현하였습니다.

프로그램에서 마이너스 값의 변환도 지원하는데, 결과값은 사용자의 입력을 받은 값과 단위를 변환하여 Sec 및 V의 단위로 출력합니다.
아래는 예는 입력값에 대한 출력 기대값입니다.

ex) 500ms -> 0.5sec
       0.83ms -> 0.00083sec
       -0.0003mV -> -3e-07V = -0.0000003V

 

사용자가 입력 시 UnitSeperation() 함수에서 값과 단위를 나누어 저장합니다.
단위가 나누어지면 UnitValueCheck() 함수에서 단위에 따라 종류 값을 임의로 설정하고, 
UnitCalculation() 함수에서 설정된 값에 따라 음수와 양수, 소수와 정수 부분에 따라 계산하는 동작을 수행합니다.

 

위 방법을 이용하면 사용자가 입력한 값이 기대치에서 벗어나면 오류를 발생시킨다든지,

다시 입력을 요구하는 상황을 설정할 수 있습니다. 

프로그램에서 시간의 단위로 s, ms, us, ns, ps를 지원하고, 전압의 단위는 V, mV, uV, nV, pV를 지원합니다.

 

결과 화면

 

 

 

전체 코드

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
#include <QCoreApplication>
#include <iostream>
 
QString UnitCalculation(QString, int);
QString UnitSeperation(QString);
int UnitValueCheck(QString);
QString m_strval;
 
int main()
{
    char input[32];
    int unitkind = 0;
 
    QString strval  = "";
    QString strunit = "";
    double inputvalue  = 0;
 
    std::cout << "Insert time and unit: ";
    std::cin >> input;
 
    strunit = UnitSeperation(QString(input));
    unitkind = UnitValueCheck(strunit);
    strval = UnitCalculation(m_strval, unitkind);
 
    inputvalue = strval.toDouble();
 
    if(strunit.contains("s"))
        std::cout << inputvalue << "sec" << std::endl;
    else
        std::cout << inputvalue << "V" << std::endl;
}
 
int UnitValueCheck(QString strunit)
{
    int nkind = 0;
 
    if(strunit == "ps")
        nkind = 1;
    else if(strunit == "ns")
        nkind = 2;
    else if(strunit == "us")
        nkind = 3;
    else if(strunit == "ms")
        nkind = 4;
    else if(strunit == "s")
        nkind = 5;
 
    if(strunit == "pV")
        nkind = 1;
    else if(strunit == "nV")
        nkind = 2;
    else if(strunit == "uV")
        nkind = 3;
    else if(strunit == "mV")
        nkind = 4;
    else if(strunit == "V")
        nkind = 5;
 
    return nkind;
}
 
QString UnitSeperation(QString str)
{
    QString strunit = "";
    QString stralp = str.toLower();
    QString strnum = str;
 
    // alpabet start
    if(str.endsWith("ps"||
       str.endsWith("ns"||
       str.endsWith("us"||
       str.endsWith("ms"||
       str.endsWith("s" ) ||
       str.endsWith("pV"||
       str.endsWith("nV"||
       str.endsWith("uV"||
       str.endsWith("mV"||
       str.endsWith("V" ))
    {
        strnum.replace(QRegExp("[A-Z, a-z]"), "");
        stralp.replace(QRegExp("[0-9, . -]"), "");
    }
    else
    {
        strunit = "";
        return strunit;
    }
 
    if     (stralp.compare("s"== 0)         strunit = "s";
    else if(stralp.compare("ps"== 0)        strunit = "ps";
    else if(stralp.compare("ns"== 0)        strunit = "ns";
    else if(stralp.compare("us"== 0)        strunit = "us";
    else if(stralp.compare("ms"== 0)        strunit = "ms";
    else if(stralp.compare("v"== 0)         strunit = "V";
    else if(stralp.compare("pv"== 0)        strunit = "pV";
    else if(stralp.compare("nv"== 0)        strunit = "nV";
    else if(stralp.compare("uv"== 0)        strunit = "uV";
    else if(stralp.compare("mv"== 0)        strunit = "mV";
    else                                      strunit = "";    // error
 
    if(strunit.compare(""!= 0)
        m_strval = strnum;
 
    return strunit;
}
 
QString UnitCalculation(QString num1, int nkind)
{
    int n = 0;
    switch(nkind)
    {
    case 1:
        n = -12// ps, pV
        break;
    case 2:
        n = -9;  // ns, nV
        break;
    case 3:
        n = -6;  // us, uV
        break;
    case 4:
        n = -3;  // ms, mV
        break;
    case 5:
        n = 0;   // s, V
        break;
    }
 
    QString strreturnval = "";
    double num1_double = num1.toDouble();
    int n_cnt = abs(n);
    int size = (num1.length()+ n_cnt) * 2;
    char *strarr = new char[size]();
 
    if(n == 0)
        return num1;
 
    int num1_length = 0;
    if(num1_double > 0)
    {
        num1_length = (int)(log10(num1_double)+1);
    }
    else if (num1_double < 0)
    {
        num1_length = num1.length()-1;
    }
 
    if(num1.contains('.'))
    {
        QStringList strlist = num1.split('.');
        int num1_length = 0;
 
        if (num1_double < 0)
            num1_length = strlist[0].length();
        else
            num1_length = strlist[0].length();
 
        if(n_cnt >= num1_length)
        {
            if (num1_double < 0)
                strcat(strarr, "-0.");
            else
                strcat(strarr, "0.");
 
            if (num1_double < 0)
                num1_length = num1_length-1;
 
            for(int i = 0; i<n_cnt-num1_length; i++)
                strcat(strarr, "0");
 
            if (num1_double < 0)
                strcat(strarr, strlist[0].right(strlist[0].length()-1).toStdString().data() );
            else
                strcat(strarr, strlist[0].right(strlist[0].length()).toStdString().data() );
 
            strcat(strarr, strlist[1].toStdString().data() );
        }
        else
        {
            if (num1_double < 0)
                strcat(strarr, (strlist[0].left(num1_length - n_cnt + 1)).toStdString().data() );
            else
                strcat(strarr, (strlist[0].left(num1_length - n_cnt)).toStdString().data() );
 
            strcat(strarr, "." );
            strcat(strarr, (strlist[0].right(n_cnt)).toStdString().data() );
            strcat(strarr, strlist[1].toStdString().data() );
        }
    }
    else
    {
        if( num1_length > n_cnt )
        {
            if (num1_double > 0)
                strcat(strarr, (num1.left(num1_length-n_cnt)).toStdString().data());
            else if (num1_double < 0)
                strcat(strarr, (num1.left(num1_length-n_cnt +1)).toStdString().data());
 
            strcat(strarr, ".");
            strcat(strarr, (num1.right(n_cnt)).toStdString().data() );
        }
        else if( num1_length <= n_cnt )
        {
            if(num1_double > 0)
                strcat(strarr,"0.");
            else if (num1_double < 0)
                strcat(strarr,"-0.");
 
            for(int i = 0; i<n_cnt-num1_length; i++)
                strcat(strarr, "0");
 
            if(num1_double > 0)
                strcat(strarr, num1.toStdString().c_str());
            else if (num1_double < 0)
                strcat(strarr, num1.right(num1_length).toStdString().c_str() );
        }
    }
 
    strreturnval = QString(strarr);
    delete[] strarr;
    return strreturnval;
}