有关进制转换

by pxz


发布于: 2012-11-26 所属分类: javascript 后端 c 算法 标签: 进制  145


<h3 id="h3-c-"><a name="c语言十进制转二进制" class="reference-link"></a><span class="header-link octicon octicon-link"></span>c语言十进制转二进制</h3><pre><code>#include <stdio.h> //十进制转二进制 char* trans2bin(int num, char* re) { int t, //临时变量 c=0, //存放余数的总数量 a[32]; //存放每一个余数 re[0] = '\0'; while(num!=0) { t = num % 2; a[c] = t; c++; num = num/2; } //倒序组合所有的余数 for (c=c-1; c>=0; c--) { sprintf(re, "%s%d", re, a[c]); } return re; } int main() { char re[32]; int i; for (i=1; i<= 20; i++) { trans2bin(i, re); printf("%d => %s \n", i, re); } } /* 运行结果: 1 => 1 2 => 10 3 => 11 4 => 100 5 => 101 6 => 110 7 => 111 8 => 1000 9 => 1001 10 => 1010 11 => 1011 12 => 1100 13 => 1101 14 => 1110 15 => 1111 16 => 10000 17 => 10001 18 => 10010 19 => 10011 20 => 10100 */ </code></pre><h3 id="h3-c-"><a name="c语言二进制转十进制" class="reference-link"></a><span class="header-link octicon octicon-link"></span>c语言二进制转十进制</h3><pre><code>#include <stdio.h> #include <string.h> #include <math.h> //二进制转十进制 int trans2ten(char* str) { int i, i_value = 0; int len = strlen(str); for (i=len-1; i>=0; i--) { if (str[i] == '1') { i_value += pow(2, len-1-i); } } return i_value; } int main() { char* a[10] = {"1", "10", "11", "100", "101", "110", "111", "1000", "1001", "1010"}; int i; for (i=0; i<10; i++) { printf("%s => %d \n", a[i], trans2ten(a[i])); } } /* 运行结果: 1 => 1 10 => 2 11 => 3 100 => 4 101 => 5 110 => 6 111 => 7 1000 => 8 1001 => 9 1010 => 10 */ </code></pre><h3 id="h3-js-"><a name="js十进制转二进制" class="reference-link"></a><span class="header-link octicon octicon-link"></span>js十进制转二进制</h3><pre><code>var num = 10; console.info(num.toString(2)); </code></pre><h3 id="h3-js-"><a name="js二进制转十进制" class="reference-link"></a><span class="header-link octicon octicon-link"></span>js二进制转十进制</h3><pre><code>console.info(parseInt('11100',2)); </code></pre>

发表评论

暂无评论

搜索
用户登陆