将长整数(十进制)转换为基数 36 字符串(C 中的 strtol 反转函数) [英] Convert long integer(decimal) to base 36 string (strtol inverted function in C)
本文介绍了将长整数(十进制)转换为基数 36 字符串(C 中的 strtol 反转函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用 strtol
函数将基于 base36 的值(保存为字符串)转换为 long int
:
I can use the strtol
function for turning a base36 based value (saved as a string) into a long int
:
long int val = strtol("ABCZX123", 0, 36);
是否有一个标准函数可以反转这个?也就是把long int
val变量转成base36字符串,再得到"ABCZX123"
?
Is there a standard function that allows the inversion of this? That is, to convert a long int
val variable into a base36 string, to obtain "ABCZX123"
again?
推荐答案
这个没有标准函数.你需要自己写一个.
There's no standard function for this. You'll need to write your own one.
使用示例:https://godbolt.org/z/MhRcNA
const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char *reverse(char *str)
{
char *end = str;
char *start = str;
if(!str || !*str) return str;
while(*(end + 1)) end++;
while(end > start)
{
int ch = *end;
*end-- = *start;
*start++ = ch;
}
return str;
}
char *tostring(char *buff, long long num, int base)
{
int sign = num < 0;
char *savedbuff = buff;
if(base < 2 || base >= sizeof(digits)) return NULL;
if(buff)
{
do
{
*buff++ = digits[abs(num % base)];
num /= base;
}while(num);
if(sign)
{
*buff++ = '-';
}
*buff = 0;
reverse(savedbuff);
}
return savedbuff;
}
这篇关于将长整数(十进制)转换为基数 36 字符串(C 中的 strtol 反转函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文