示例:
/*** @brief how about carry-bin-otc? show you here.* @author wen`xuanpei* @email 15873152445@163.com(query for any question here)*/
#define _CRT_SECURE_NO_WARNINGS//support c-library in Microsoft-Visual-Studio
#include <stdio.h>
#include <string.h>/*** @brief transform binary-string-number to octal-string-number.* @param* ostr:output octal-string-number(must have enough space)* bstr:input binary-string-number(strlen(bstr) % 3 == 0)* @return ostr*/
static char* bin2otc(char *ostr, char const*bstr){char const* const end = bstr + strlen(bstr);char *po = ostr;while(bstr + 3 <= end){*po++ = ( (bstr[0]-'0')<<2 | (bstr[1]-'0') << 1 | (bstr[2]-'0') ) + '0';bstr += 3;}*po = '\0';return ostr;
}
static void test_bin_to_otc(){char const*bstr = "000001010011100101110111";char ostr[8+1] = {0};printf("'%s' => '%s'\n", bstr, bin2otc(ostr, bstr) );
}/*** @brief transform octal-string-number to binary-string-number.* @param* bstr:output binary-string-number(must have enough space)* ostr:input octal-string-number* @return bstr*/
static char* otc2bin(char *bstr, char const*ostr){char *pb = bstr;char oCh;while( (oCh = *ostr++) ){switch(oCh){default:break;case '0':pb[0] = '0', pb[1] = '0', pb[2] = '0', pb += 3;break;case '1':pb[0] = '0', pb[1] = '0', pb[2] = '1', pb += 3;break;case '2':pb[0] = '0', pb[1] = '1', pb[2] = '0', pb += 3;break;case '3':pb[0] = '0', pb[1] = '1', pb[2] = '1', pb += 3;break;case '4':pb[0] = '1', pb[1] = '0', pb[2] = '0', pb += 3;break;case '5':pb[0] = '1', pb[1] = '0', pb[2] = '1', pb += 3;break;case '6':pb[0] = '1', pb[1] = '1', pb[2] = '0', pb += 3;break;case '7':pb[0] = '1', pb[1] = '1', pb[2] = '1', pb += 3;break;}}*pb = '\0';return bstr;
}
static void test_otc_to_bin(){char const*ostr = "01234567";char bstr[8*3+1] = {0};printf("'%s' => '%s'\n", ostr, otc2bin(bstr, ostr));
}int main(){test_bin_to_otc();test_otc_to_bin();getchar();return 0;
}
1)编译运行
2)要点分析
1)二进制=>八进制,以三比一的个数比例进行映射
2)八进制=>二进制,以一比三的个数比例进行映射
尾声:
其它不明白的地方不用过于纠结,那只是在浪费时间。学得多了,回过头来看自然融会贯通。