I am completely new to coding and have got this solution to another post working. I was wondering if there was a way to get it to work with negative integers as an input. I don't have access to the c standard libraries, hence my attempt to reproduce this post.
Asked
Active
Viewed 295 times
0
-
1What is your question. You already have almost an answer... Just check if the number is negative and output a `-`. But anyway, if you are completely new to coding I suggest you start with some simpler exercises. – Jabberwocky Mar 26 '22 at 08:54
-
Man I wish that was possible. I really do, thanks for the suggestion. I know how to check if its negative, but how do I output the minus? or better yet, how do I read in the negative in if my function is like: function(int value, char buffer, radix) – Reaper373 Mar 26 '22 at 08:59
1 Answers
0
Just check if the number is negative and prefix the -
symbol:
#include <stdio.h>
char* int2basestr (int num, char* str, int radix) {
// extend the base as necessary
char base[] = "0123456789ABCDEFGH"; // IJKLMN ....
if (radix < 2 || radix > (sizeof(base) -1)) { // radix supported?
printf ("\nRadix/Base[%d] not yet supported, extend it\n", radix);
str[0] = '\0';
return str;
}
int si = 0;
if (num < 0) {
str[si++] = '-';
num = -num;
}
char tmp[256];
int rdi = -1;
while (num) {
tmp[++rdi] = base[num % radix];
num /= radix;
}
while (rdi >= 0)
str[si++] = tmp[rdi--];
str[si] = '\0';
return str;
}
#define TEST_COUNT 7
int main () {
int values [TEST_COUNT] = { 12, -342, 332, -232, 675, +880, 34423 };
int bases [TEST_COUNT] = {2, 3, 4, 5, 6, 16, 25};
char strnum[256];
for (int ti = 0; ti < TEST_COUNT; ++ti) {
printf ("Num[%d] in Base[%d] is : [%s]\n", values[ti], bases[ti],
int2basestr (values[ti], strnum, bases[ti]));
}
return 0;
}

जलजनक
- 3,072
- 2
- 24
- 30
-
I had problems getting this one to work completely with my compiler but I did learn a TON from your structure. Thank you VERY much. (I did end up solving it by apply this post to my own code set. https://stackoverflow.com/a/9660930/18586829 ) Thanks again! – Reaper373 Mar 26 '22 at 12:02