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
|
// 제곱근
int power(int value, int num){
int result = 1;
for (int i = 0; i < num; i++)
result *= value;
return result;
}
// 진수변환하기 (2,4,8,16 진수를 10진수로 변환)
// input ex) B, Q, O, H (순서대로, 2, 4, 8, 16진수)
// 2진수 양수 ) 1.0.1.1.B or +1.1.0.B
// 4진수 음수 ) -3.0.1.1.Q
// 16진수 음수 ) -A.9.F.H
int converToDec(char * str, int length, int type){
int count = 0;
// 해당 진수의 재곱근하여 자리수를 찾음.
count = power(type, (length + 1) / 2 -1);
int result = 0;
char tempStr[50] = { 0, };
int start = 0;
int end = 0;
bool minus = false;
int atoi = 0;
for (int i = 0; i <= length; i++){
if (*(str + i) == '.'){
end = i;
stringCopy(tempStr, str, start, end);
atoi = asciiToInteger(tempStr);
result += atoi * count;
start = end + 1;
count /= type;
}
else if (*(str + i) == '-'){ // 음수일경우
start = i + 1;
minus = true;
}
else if (*(str + i) == '+'){ // 양수일경우
start = i + 1;
}
}
if (minus)
return -result;
return result;
}
| cs |
2015년 2월 12일 목요일
[Basic Skill] 2,4,8,16진수 -> 10진수 변환하기
라벨:
진수변환,
함수구현,
Basic skill,
C언어
2014년 12월 18일 목요일
[Basic Skill] 문자를 Integer로 변환하기 (Ascii to Integer)
문자열을 int형으로 변환하기 위해서는 0~10 이라는 숫자를 표시하는 문자에
'0' 이라는 숫자를 나타내는 Ascii 값인 48을 빼주면 된다.
간단히 말해
0 이라는 문자는 Ascii 값 48 이고, 1이라는 문자는 Ascii값 49... 로 되어 있기 때문에
예로 2라는 숫자는 50 이라는 Ascii 코드로 약속 되어 있기 때문에
50 - 48 을 통해 2 라는 숫자가 나오고, 그 2라를 값을 int형으로 지정하면 된다.
'0' 이라는 숫자를 나타내는 Ascii 값인 48을 빼주면 된다.
간단히 말해
0 이라는 문자는 Ascii 값 48 이고, 1이라는 문자는 Ascii값 49... 로 되어 있기 때문에
예로 2라는 숫자는 50 이라는 Ascii 코드로 약속 되어 있기 때문에
50 - 48 을 통해 2 라는 숫자가 나오고, 그 2라를 값을 int형으로 지정하면 된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
// 문자형 숫자를 Integer로 변환하기 (1~10, A~F)
int asciiToInteger(const char * str){
int result = 0;
while (*str){
if (*str >= '0' && *str <= '9'){ // 0~9 의 문자일 경우
result = result * 10 + *str - '0';
}
else if (*str >= 'A' && *str <= 'F'){ // A~F의 문자일 경우
result = result * 10 + (*str - 'A') + 10;
}
str++;
}
return result;
}
| cs |
[Basic Skill] 문자열 복사 (strcpy) 구현하기
문자를 복사하기 위해서는 해당 문자열의 시작과 끝 위치를 정해서 아래와 같이
문자열 복사가 가능함.
문자열 복사가 가능함.
1
2
3
4
5
6
7
8
|
void stringCopy(char *dest, const char *src, int start, int end){
int i = 0;
for (int i = 0; i < end - start; i++){
*(dest + i) = *(src + start + i);
}
// printf("stringCopy dest %s src %s \n", dest, src);
return;
}
| cs |
[Basic Skill] 문자열의 길이 구현하기 strLength
문자열의 길이를 구하기 위해서 문자 배열의 길이를 구하면 됨.
문자 배열에서 '\0' 혹은 'NULL' 을 만나기 전 까지 count 하면 그게 문제 길이가 됩니다.
문자 배열에서 '\0' 혹은 'NULL' 을 만나기 전 까지 count 하면 그게 문제 길이가 됩니다.
1
2
3
4
5
6
7
8
|
int strLength(const char *str){
int strlen = 0;
while (*(str++) != '\0'){
strlen++;
};
// printf("string length = %d \n", strlen);
return strlen;
}
| cs |
피드 구독하기:
글 (Atom)