将长整数(十进制)转换为基数为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屋!
查看全文