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

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

#1 fix makefile for multi-platform

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
31 * 16진수 문자열을 저장할 메모리가 미리 할당되어야 하며, <br />
32 * 크기는 null-character를 포함하여 len * 2 + 1
33 */
34int
35CF_Codec_BinaryToHex (const unsigned char * bin,
36 const size_t len,
37 char * hex)
38{
39 size_t iter = 0;
40 size_t count = len * 2 + 1;
41
42 const char hexchar[] = {'0', '1', '2', '3',
43 '4', '5', '6', '7',
44 '8', '9', 'a', 'b',
45 'c', 'd', 'e', 'f'};
46
47 const __uchar * ptr = bin;
48
49 ASSERT_ARGS (bin == NULL);
50 ASSERT_ARGS (hex == NULL);
51
52 for (iter = 0 ; iter < count ; iter += 2, ptr++)
53 {
54 hex[iter ] = hexchar[((*(ptr)) >> 4) & 0x0f];
55 hex[iter + 1] = hexchar[((*(ptr)) ) & 0x0f];
56 }
57 hex[count - 1] = '\0';
58
59 return CF_OK;
60}
61
62/**
63 * 16진수 문자열을 바이너리 데이터로 변환
64 *
65 * @return 성공 시, CF_OK; 실패 시, 오류 코드
66 *
67 * @param hex 16진수 문자열
68 * @param bin 바이너리 데이터를 저장할 주소
69 * @param len 바이너리 데이터의 길이를 저장할 주소
70 *
71 * @remark
72 * 바이너리 데이터를 저장할 메모리가 미리 할당되어야 하며, <br />
73 * 크기는 strlen (hex) / 2
74 */
75int
76CF_Codec_HexToBinary (const char * hex,
77 unsigned char * bin,
78 size_t * len)
79{
80 int result = 0;
81
82 size_t length = strlen (hex); /* absolutely even-number */
83 size_t iter = 0;
84 size_t count = length / 2;
85 int twochar = 0;
86
87 const char * ptr = hex;
88 char buf = 0;
89 __uchar val = 0;
90
91 ASSERT_ARGS (hex == NULL);
92 ASSERT_ARGS (bin == NULL);
93 ASSERT_ARGS (len == NULL);
94
95 for (iter = 0 ; iter < count ; iter++)
96 {
97 for (twochar = 2, val = 0 ; twochar ; ptr++, twochar--)
98 {
99 buf = *ptr;
100 val = (__uchar)(val << 4);
101
102 if (IS_NUMBER (buf)) val |= (__uchar)(buf - '0' + 0);
103 else if (IS_LOWERCASE (buf)) val |= (__uchar)(buf - 'a' + 10);
104 else if (IS_UPPERCASE (buf)) val |= (__uchar)(buf - 'A' + 10);
105 else
106 {
107 result = CF_ERROR_CODEC_NOT_HEXSTRING;
108 break;
109 }
110 }
111
112 bin[iter] = val;
113 }
114
115 if (result == 0)
116 *len = count;
117
118 return result;
119}
Note: See TracBrowser for help on using the repository browser.