Anonymous user
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 <
#include <stdint.h>
▲char *to_base(long num, int base)
{
uint64_t n;
▲ char t;
int i, len = 0, neg = 0;
if (base > 36) {
fprintf(stderr, "base %d too large\n", base);
}
/* safe against most negative integer */
n = ((neg = num < 0)) ? (~num) + 1 : num;
do { buf[len++] = tbl[n % base]; } while(n /= base);
out = malloc(len + neg + 1);
for (i = neg; len > 0;
if (neg) out[0] = '-';
t = result[j];▼
▲ return result;
}
long from_base(const char *num_str, int base)
{
int result = strtol(num_str, &endptr, base);▼
* unsigned long long, respectively */
▲ return result;
▲ /* there is also strtoul() for parsing into an unsigned long */
▲ /* in C99, there is also strtoll() and strtoull() for parsing into long long and unsigned long long, respectively */
}
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++}}==
|