So I am an absolute beginner in C and I have to make a decimal to hexadecimal converter.
So I guess I would need to make a loop that loops until the result is 0.
But how do I make it remember all the remainders? The number is going to be input with scanf so I can't tailor the code to it.
Now I would want to do something like this
while(number(n)!=0)
{
number0 / 16 = number1
number0 % 16 = remainder0
number1 / 16 = number2
number1 % 16 = remainder1
.....
number(n-1) / 16 = 0
number(n-1) % 16 = lastremainder
}
hex = lastremainder, ..., remainder2, remainder1, remainder0
But how can I make the program create variables during the loop? Do I have to use a complete different method? I took a look at other decimal to hex converters and I don't quite get how they work.
Like I said I am an absolute beginner so sorry if the question is stupid.
Thank you for the replies. So arrays are the answer to my problem? I don't fully understand them right now but thank you for the point in the right direction.
If you want to be able to get size unlimited number, you need to use dynamic array. firstly you get the input-length by loop, and then allocate array as needed. you need to increase an index in your loop and put the current value in array[index].
Make an array and write the remains in it:
The line
array[counter]=number%16;
means that the first element in the array will be number%16 - the second will be (number/16)%16 etc.You need the
counter
to know how many elements there is in the array (how much remains), so that you can later write them backwards.(Take into consideration here that you have a limit -
int array[50];
because, what happens if your number is really big and you have more than 50 remains? The solution would be to write this dynamically, but I don't think you should worry about that at this point.)Just try this:
I'd simply use
sprintf
, to be honest:Job done...
In full, your code could look something like:
Or even: