求教,将一个64位的二进制数如何转换为一个十进制的数
最大的十进制数快二十位了,该怎样处理呀?
其实我一直很纳闷这个问题。数就是数,要说转换只是在显示形式上转换而已。与运算无关。
64位,用long long型接收就好了格式串是"%lld"或"%I64d"。
如果输入的就是一串01,那可以用字符串接收,之后移位拼一个long long数出来。
#include <stdio.h> #include <string.h> typedef unsigned long long ull; static ull map[64] = { 1, 2llu, 4llu, 8llu, 16llu, 32llu, 64llu, 128llu, 256llu, 512llu, 1024llu, 2048llu, 4096llu, 8192llu, 16384llu, 32768llu, 65536llu, 131072llu, 262144llu, 524288llu, 1048576llu, 2097152llu, 4194304llu, 8388608llu, 16777216llu, 33554432llu, 67108864llu, 134217728llu, 268435456llu, 536870912llu, 1073741824llu, 2147483648llu, 4294967296llu, 8589934592llu, 17179869184llu, 34359738368llu, 68719476736llu, 137438953472llu, 274877906944llu, 549755813888llu, 1099511627776llu, 2199023255552llu, 4398046511104llu, 8796093022208llu, 17592186044416llu, 35184372088832llu, 70368744177664llu, 140737488355328llu, 281474976710656llu, 562949953421312llu, 1125899906842624llu, 2251799813685248llu, 4503599627370496llu, 9007199254740992llu, 18014398509481984llu, 36028797018963968llu, 72057594037927936llu, 144115188075855872llu, 288230376151711744llu, 576460752303423488llu, 1152921504606846976llu, 2305843009213693952llu, 4611686018427387904llu, 9223372036854775808llu }; int main(void) { ull decimal = 0; int i, j; char binary[65]; j = strlen(gets(binary)); for (i = 0; j--; ++i) decimal += (binary[j] - '0') ? map[i] : 0; printf("%llu\n", decimal); return 0; }