如何在C中将十进制转换为十六进制转换器 [英] How to make a decimal to hexadecimal converter in C

查看:415
本文介绍了如何在C中将十进制转换为十六进制转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我是C中的绝对新手,我必须将十进制转换为十六进制。



所以我想我需要做一个循环,直到结果为0为止。



我是否记得所有剩下的东西?这个号码是用scanf输入的,所以我无法调整代码。



现在我想要做这样的事情了

  while(number(n)!= 0)
{
number0 / 16 = number1
number0%16 =余数0
number1 / 16 = number2
number1%16 =余数1
.....
number(n-1)/ 16 = 0
number(n- 1)%16 = lastremainder
}

十六进制= lastremainder,...,余数2,余数1,余数0

但是我怎样才能让循环中的程序创建变量?我必须使用完全不同的方法吗?我看了一下其他十进制到十六进制转换器,我不太清楚它们是如何工作的。



像我说过的,如果问题很蠢,我是一个绝对的初学者。抱歉!

谢谢回复。所以阵列是我的问题的答案?我现在还没有完全理解它们,但是感谢你向正确的方向指出了一切。 解决方案

创建一个数组并写入其中的遗留物:

  int数组[50]; 
int counter = 0;

[...]

while(number!= 0)
{
[...]

阵列[计数器] =号%16;
number / = 16;
++ counter;



$ b $ array [counter] = number%16 ; 表示数组中的第一个元素为数字%16 - 第二个元素为(数字/ 16)%16等。

您需要 counter 来知道数组中有多少元素(剩下多少元素),以便稍后将它们向后写入。



(请注意,您有一个限制 - int数组[50]; 你的电话号码真的很大,你剩下的电话号码超过50个了吗?解决办法是动态地写出这个号码,但我认为你不应该担心这一点。)


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.

解决方案

Make an array and write the remains in it:

int array[50];
int counter=0;

[...]

while(number!=0)
{
   [...]

   array[counter]=number%16;
   number/=16;
   ++counter;
}

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.)

这篇关于如何在C中将十进制转换为十六进制转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆