Linux C 快速的八进制转二进制实现

一种快速的 八进制 转 二进制 C语言 实现。

code

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
chunli@blog:~/source/oct$ cat main.c
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char isoctal[]={
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0
};

const char*
octal2binary(const char *str, int len, char *buff, int size)
{
int offset = 0;
int index = 0;
while(offset < len && index < size)
{
//至少剩余4字符, 以\开头, 3位数字结尾, 尾部检测
unsigned char char0 = str[offset+0];
unsigned char char1 = str[offset+1];
unsigned char char2 = str[offset+2];
unsigned char char3 = str[offset+3];
unsigned char char4 = str[offset+4];
if(len - offset >= 4 && '\\' == char0 && isoctal[char1] && isoctal[char2] && isoctal[char3] && !isdigit(char4))
{
buff[index++] = strtoul(str + offset + 1, NULL, 8);
offset +=4;
}
else
{
buff[index++] = str[offset++];
}
}
return buff;
}

int main()
{
char buff[64];
const char *p = "Hello World! \\344\\270\\255\\346\\226\\207ABC\\346\\265\\213\\350\\257\\225\\345\\255\\227\\347\\254\\246\\344\\270\\262\\056";
printf("%s\n",p);

octal2binary(p, strlen(p), buff, sizeof(buff));
printf("%s\n", buff);
}
chunli@blog:~/source/oct$

编译运行

1
2
3
4
chunli@blog:~/source/oct$ gcc -Wall   main.c  && ./a.out
Hello World! \344\270\255\346\226\207ABC\346\265\213\350\257\225\345\255\227\347\254\246\344\270\262\056
Hello World! 中文ABC测试字符串.
chunli@blog:~/source/oct$