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

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

#1 add codec module (bin <-> hex-string)

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
19/**
20 * 바이너리 데이터를 16진수 문자열로 변환
21 *
22 * @return 성공 시, CF_OK; 실패 시, 오류 코드
23 *
24 * @param bin 바이너리 데이터
25 * @param len 바이너리 데이터 길이
26 * @param hex 16진수 문자열을 저장할 주소
27 *
28 * @remark 16진수 문자열을 저장할 메모리가 미리 할당되어야 하며, 크기는 len * 2 + 1
29 */
30int
31CF_Codec_BinaryToHex (const unsigned char * bin,
32 const size_t len,
33 char * hex)
34{
35 size_t iter = 0;
36 size_t count = len * 2 + 1;
37
38 char hexchar[] = {'0', '1', '2', '3',
39 '4', '5', '6', '7',
40 '8', '9', 'a', 'b',
41 'c', 'd', 'e', 'f'};
42
43 const unsigned char * ptr = bin;
44
45 ASSERT_ARGS (bin == NULL);
46 ASSERT_ARGS (hex == NULL);
47
48 for (iter = 0 ; iter < count ; iter += 2, ptr++)
49 {
50 hex[iter ] = hexchar[((*(ptr)) >> 4) & 0x0f];
51 hex[iter + 1] = hexchar[((*(ptr)) ) & 0x0f];
52 }
53 hex[count] = '\0';
54
55 return CF_OK;
56}
57
58/**
59 * 16진수 문자열을 바이너리 데이터로 변환
60 *
61 * @return 성공 시, CF_OK; 실패 시, 오류 코드
62 *
63 * @param hex 16진수 문자열
64 * @param bin 바이너리 데이터를 저장할 주소
65 * @param len 바이너리 데이터의 길이를 저장할 주소
66 *
67 * @remark 바이너리 데이터를 저장할 메모리가 미리 할당되어야 하며, 크기는 strlen (hex) / 2
68 */
69int
70CF_Codec_HexToBinary (const char * hex,
71 unsigned char * bin,
72 size_t * len)
73{
74 typedef unsigned char __uchar;
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.