反转字符串
基本上我有一个方法可以将十进制数转换为不同基数(例如,基数 2)中的数字,数组位置 0 中的元素是最重要的,例如 $100,1 是最重要的。
如果我输入一个应该输出 AC 的字符串,我会得到 CA(十进制到十六进制)。如何在 C 中反转这个 char 数组?
char* decimalToRadixN(int decimalNumber, int radixN, char result[]){
/*
If its below base 10, its going to be a digit convertsion (ex to binary)
If it's above base 10, we need to call a method to convert the char to a symbol.
*/
//char swap[] = result[];
int count = 0;
while(decimalNumber>0)
{
int remain = decimalNumber % radixN;
result[count] = decimalToSymbol(remain);
decimalNumber = decimalNumber / radixN;
count++;
}
/*
for(int i = 0; i < count; i++)
{
reverse the array
}
*/
return result;
}
Basically I have a method that converts a decimal number to a number in a different base (ex, base 2), the element in position 0 of the array is the most significant, ex $100, The 1 is the most significant.
If i put in a string that is supposed to output AC, I get CA (Dec to hex). How do I reverse this char array in C?
char* decimalToRadixN(int decimalNumber, int radixN, char result[]){
/*
If its below base 10, its going to be a digit convertsion (ex to binary)
If it's above base 10, we need to call a method to convert the char to a symbol.
*/
//char swap[] = result[];
int count = 0;
while(decimalNumber>0)
{
int remain = decimalNumber % radixN;
result[count] = decimalToSymbol(remain);
decimalNumber = decimalNumber / radixN;
count++;
}
/*
for(int i = 0; i < count; i++)
{
reverse the array
}
*/
return result;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不完全是问题的答案,但为什么不首先以正确的顺序写下数字呢?
毫无疑问,您不知道需要多少位数字,因此从哪里开始写。
这可以通过将数字的对数取到基数的底数来完成。这可以使用对数规则来完成。
[ 另请注意,您的 'decimalNumber' 从来都不是真正的小数。它是一个 C
int
,真正的二进制。这只是命名,没有区别。printf()
中显示为基数 10 是对printf()
的解释,而不是数字本身。]现在您已获得给定基数中的位数,只需写入该数字并递减而不是递增。
另外,如果您传入结果的可用长度,您可以预先根据可用长度验证所需的长度,如果是,则返回错误代码(例如
NULL
)。并且不要忘记以 null 终止,或者以其他方式提供对返回写入字符串长度的支持。
Not quite the answer to the question as asked, but why not just write the digits in the right order in the first place?
No doubt you didn't know how many digits you needed, hence where to start writing.
This can be done by taking the log of the number to the base of the radix. This can be done using the rules of logarithms.
[ Note also that your 'decimalNumber' is never really a decimal. It is a C
int
, really binary. This is just naming, and makes not difference. That it appears as base 10 fromprintf()
is the interpretation ofprintf()
, not the number itself.]Now you have the number of digits in the given base, just write to that digit and decrement rather than increment.
Also, if you pass in the available length of result, you can verify the needed against available length up front and return an error code ( e.g.
NULL
) if so.And don't forget to null terminate, or otherwise provide support for returning the length of the written character string.