Non-decimal radices/Convert: Difference between revisions

→‎{{header|C}}: overflow; correct string length; output
(→‎{{header|C}}: overflow; correct string length; output)
Line 229:
<lang c>#include <stdlib.h>
#include <string.h>
#include <assertstdio.h>
#include <stdint.h>
 
char *to_base(longint64_t num, int base)
#define MAX_OUTSTR_LEN 65
char *to_base(long num, int base)
{
static const char *maptbl = "0123456789abcdefghijklmnopqrstuvwxyz";
char *resultbuf[66] = NULL{'\0'};
char t*out;
int i=0, j;
uint64_t n;
char t;
int i, len = 0, neg = 0;
if (base > 36) {
fprintf(stderr, "base %d too large\n", base);
return result0;
}
 
/* safe against most negative integer */
if ( base > strlen(map) ) return NULL;
n = ((neg = num < 0)) ? (~num) + 1 : num;
 
do { buf[len++] = tbl[n % base]; } while(n /= base);
result = malloc(sizeof(char)*MAX_OUTSTR_LEN);
 
*result = 0;
out = malloc(len + neg + 1);
do {
for (i = neg; len > 0; result[i++) out[i] = mapbuf[ num%base --len];
if (neg) out[0] = '-';
num /= base;
 
} while(num != 0);
return resultout;
result[i] = 0;
for(j=0; j < i/2; j++) { /* invert the rests */
t = result[j];
result[j] = result[i-j-1];
result[i-j-1] = t;
}
return result;
}
 
long from_base(const char *num_str, int base)
{
char *endptr;
/* there is also strtoul() for parsing into an unsigned long */
int result = strtol(num_str, &endptr, base);
/* in C99, there is also strtoll() and strtoull() for parsing into long long and unsigned long long, respectively */
assert(*endptr == '\0'); /* if there are any characters left, then string contained invalid characters */
* unsigned long long, respectively */
return result;
int result = strtol(num_str, &endptr, base);
/* there is also strtoul() for parsing into an unsigned long */
t = return result[j];
/* in C99, there is also strtoll() and strtoull() for parsing into long long and unsigned long long, respectively */
}
}</lang>
 
int main()
{
int64_t x;
x = ~(1LL << 63) + 1;
printf("%lld in base 2: %s\n", x, to_base(x, 2));
x = 383;
printf("%lld in base 16: %s\n", x, to_base(x, 16));
return 0;
}</lang>output<lang>-9223372036854775808 in base 2: -1000000000000000000000000000000000000000000000000000000000000000
383 in base 16: 17f</lang>
 
=={{header|C++}}==
Anonymous user