C++ convert binary to decimal for bit values greater than 64 bits -
i using code convert binary decimal. code not work more 64 bits __int64 holds 8 bytes. please tell suggest algorithm use convert more 64 bits decimal values. end result has string. appreciated. thanks.
int bin2dec(char *bin) { __int64 b, k, m, n; __int64 len, sum = 0; len = strlen(bin) - 1; for(k = 0; k <= len; k++) { n = (bin[k] - '0'); // char numeric value if ((n > 1) || (n < 0)) { puts("\n\n error! binary has 1 , 0!\n"); return (0); } for(b = 1, m = len; m > k; m--) { // 1 2 4 8 16 32 64 ... place-values, reversed here b *= 2; } // sum sum = sum + n * b; } return(sum); }
typically, when dealing data bigger can store in 1 integer unit, solution 1 of 2 things:
- use character array/string store value "ascii" (in 1 bit per char)
- use multiple integers in array store values, using
xbits per element.
there nothing particularly different conversion, once have done x bits, shift next element.
by way:
int bin2dec(char *bin) { int k, n; int len; __int64 sum = 0; len = strlen(bin); for(k = 0; k < len; k++) { n = (bin[k] - '0'); // char numeric value if ((n > 1) || (n < 0)) { puts("\n\n error! binary has 1 , 0!\n"); return (0); } // sum sum <<= 1; sub += n; } return(sum); } is bit simpler.
Comments
Post a Comment