简体   繁体   English

将C中的十六进制转换为十进制

[英]Converting hex to decimal in C

For example, when 例如,当

val = 0x505050
val1 = 0x005000

The result should be the addtion of the two hexadecimals, which is: 结果应该是两个十六进制的加法,即:

0x50a050

What I did is: 我所做的是:

int hex;
int channel;
int result;

printf("first hex number: ");
scanf("%x", &hex);

printf("second hex number: ");
scanf("%x", &channel);

result = hex + channel;
printf("Your new hex value is: ");
printf("0x%x\n", result);

And this brought me the right result. 这给了我正确的结果。 However, the problem here is that, when the second (channel) value is like, 但是,这里的问题是,当第二个(通道)值是

50 00 00

it is base 10, not 16 so the addition of 0x505050 and 50 00 00 should be 0x825050 but I get 0x5050a0. 它是以10为底,而不是16,所以0x505050和50 00 00的加法应该是0x825050,但我得到0x5050a0。

How can I manage this problem? 我该如何解决这个问题? Also, when the second input is not hex and it is negative, for example, 同样,例如,当第二个输入不是十六进制且为负数时,

-50 -40 -30

I get 0x505000, but it should be 0x1e2832 我得到0x505000,但是应该是0x1e2832

How can handle with negative numbers? 如何处理负数?

Can someone please help me out with this problem? 有人可以帮我解决这个问题吗?

You will have to gather your input as text, and then go through logic of your own creation to figure out if the text should be interpreted as base16, base10, or something else: 您将必须将输入收集为文本,然后通过自己创建的逻辑来弄清楚是否应将文本解释为base16,base10或其他形式:

char input[1024];
fgets(input, 1024, stdin);
// Examine input to figure out if base16, or base10.


You also wrote that 500000(base10) + 0x505050(base16) should be 0x825050(base16) . 您还写道500000(base10) + 0x505050(base16)应该是0x825050(base16) But when I add those together, I get 0x57F170(base16) . 但是,当我将它们加在一起时,我得到0x57F170(base16)
Please clarify your math? 请澄清你的数学?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM