source: libcf/trunk/src/cf_codec.c@ 72

Last change on this file since 72 was 72, checked in by cheese, 11 years ago

#1 modify test code and data-type in codec

File size: 2.6 KB
Line 
1/**
2 * @file cf_codec.c
3 * @author myusgun <myusgun@gmail.com>
4 */
5#include "cf_codec.h"
6#include "cf_error.h"
7
8#include <string.h>
9#include <stdio.h>
10
11#define ASSERT_ARGS(x) \
12 if ((x)) \
13 return CF_ERROR_CODEC_INVALID_ARGS
14
15#define IS_NUMBER(x) (x >= '0' && x <= '9')
16#define IS_LOWERCASE(x) (x >= 'a' && x <= 'f')
17#define IS_UPPERCASE(x) (x >= 'A' && x <= 'F')
18
19typedef unsigned char __uchar;
20
21/**
22 * 바이너리 데이터를 16진수 문자열로 변환
23 *
24 * @return 성공 시, CF_OK; 실패 시, 오류 코드
25 *
26 * @param bin 바이너리 데이터
27 * @param len 바이너리 데이터 길이
28 * @param hex 16진수 문자열을 저장할 주소
29 *
30 * @remark 16진수 문자열을 저장할 메모리가 미리 할당되어야 하며, 크기는 len * 2 + 1
31 */
32int
33CF_Codec_BinaryToHex (const unsigned char * bin,
34 const size_t len,
35 char * hex)
36{
37 size_t iter = 0;
38 size_t count = len * 2 + 1;
39
40 const char hexchar[] = {'0', '1', '2', '3',
41 '4', '5', '6', '7',
42 '8', '9', 'a', 'b',
43 'c', 'd', 'e', 'f'};
44
45 const __uchar * ptr = bin;
46
47 ASSERT_ARGS (bin == NULL);
48 ASSERT_ARGS (hex == NULL);
49
50 for (iter = 0 ; iter < count ; iter += 2, ptr++)
51 {
52 hex[iter ] = hexchar[((*(ptr)) >> 4) & 0x0f];
53 hex[iter + 1] = hexchar[((*(ptr)) ) & 0x0f];
54 }
55 hex[count - 1] = '\0';
56
57 return CF_OK;
58}
59
60/**
61 * 16진수 문자열을 바이너리 데이터로 변환
62 *
63 * @return 성공 시, CF_OK; 실패 시, 오류 코드
64 *
65 * @param hex 16진수 문자열
66 * @param bin 바이너리 데이터를 저장할 주소
67 * @param len 바이너리 데이터의 길이를 저장할 주소
68 *
69 * @remark 바이너리 데이터를 저장할 메모리가 미리 할당되어야 하며, 크기는 strlen (hex) / 2
70 */
71int
72CF_Codec_HexToBinary (const char * hex,
73 unsigned char * bin,
74 size_t * len)
75{
76 int result = 0;
77
78 size_t length = strlen (hex); /* absolutely even-number */
79 size_t iter = 0;
80 size_t count = length / 2;
81 int twochar = 0;
82
83 const char * ptr = hex;
84 char buf = 0;
85 __uchar val = 0;
86
87 ASSERT_ARGS (hex == NULL);
88 ASSERT_ARGS (bin == NULL);
89 ASSERT_ARGS (len == NULL);
90
91 for (iter = 0 ; iter < count ; iter++)
92 {
93 for (twochar = 2, val = 0 ; twochar ; ptr++, twochar--)
94 {
95 buf = *ptr;
96 val = (__uchar)(val << 4);
97
98 if (IS_NUMBER (buf)) val |= (__uchar)(buf - '0' + 0);
99 else if (IS_LOWERCASE (buf)) val |= (__uchar)(buf - 'a' + 10);
100 else if (IS_UPPERCASE (buf)) val |= (__uchar)(buf - 'A' + 10);
101 else
102 {
103 result = CF_ERROR_CODEC_NOT_HEXSTRING;
104 break;
105 }
106 }
107
108 bin[iter] = val;
109 }
110
111 if (result == 0)
112 *len = count;
113
114 return result;
115}
Note: See TracBrowser for help on using the repository browser.